from wxPython.wx import *
import sys

# Find the installation dir of snarfzilla
if sys.path[0] == "":
    snarfdir = "."
else:
    snarfdir = sys.path[0]

class panelupload(wxPanel):
    def __init__(self, parent, sb):
        wxPanel.__init__(self, parent, -1)
        self.sb = sb
        #self.log=log
        #self.keylist=keylist
        self.parent=parent
        self.process = None

#                EVT_IDLE(self, self.OnIdle)
        EVT_END_PROCESS(self, -1, self.OnProcessEnded)


        #----------------------------------------------------------------------------------
        # Options at top (Box 1)
        #----------------------------------------------------------------------------------

        box1 = wxBoxSizer(wxHORIZONTAL)
        checkBoxId = wxNewId()
        htlId = wxNewId()
        self.chkKeyIndex = wxCheckBox(self, checkBoxId, "Send to Key Index", style=wxNO_BORDER)
        #self.addtokeyring = wxCheckBox(self, checkBoxId + 1, "Add to Keyring", style=wxNO_BORDER)
        self.lblhtl= wxStaticText(self, -1, "                        Hops to Live ")
        self.htl = wxTextCtrl(self, htlId, "50")
        box1.Add(self.chkKeyIndex, 1, wxALIGN_LEFT, 0)
        #box1.Add(self.addtokeyring, 1, wxALIGN_LEFT, 0)
        box1.Add(self.lblhtl, 1, wxRIGHT, 0)
        box1.Add(self.htl, 1, wxRIGHT, 0)

        #self.addtokeyring.SetValue(false)
        self.chkKeyIndex.SetValue(false)
        #----------------------------------------------------------------------------------
        # Output wxTextCtrl (self.out)
        #----------------------------------------------------------------------------------

        self.out = wxTextCtrl(self, -1, '', style=wxTE_MULTILINE|wxTE_READONLY)

        #----------------------------------------------------------------------------------
        # "list" wxListCtrl log window (Box 2)
        #----------------------------------------------------------------------------------
        listID = wxNewId()
        self.list= wxListCtrl(self, listID, size=wxDefaultSize,style=wxLC_REPORT|wxSUNKEN_BORDER)
        self.list.InsertColumn(0,"Key")
        self.list.InsertColumn(1,"Filename")
        self.list.InsertColumn(2,"Status")
        #self.list.InsertColumn(2,"Size")
        self.list.SetColumnWidth(0, 305)
        self.list.SetColumnWidth(1, 305)
        self.list.SetColumnWidth(2, 70)
        #self.list.SetColumnWidth(2, 70)

        box2 = wxBoxSizer(wxHORIZONTAL)
        box2.Add(self.list, 1, wxEXPAND|wxALL,0)

        #Events:

        # for wxMSW
        EVT_COMMAND_RIGHT_CLICK(self.list, listID, self.OnRightClick)

        # for wxGTK
        EVT_RIGHT_UP(self.list, self.OnRightClick)
        EVT_RIGHT_DOWN(self.list, self.OnRightDown)

        #--------------------------------------------------------------------------------
        #Bottom input boxes, buttons (Box 3)
        #---------------------------------------------------------------------------------
        self.inp = wxTextCtrl(self, -1, '', style=wxTE_PROCESS_ENTER)
        self.fileLabel = wxStaticText(self, -1, 'Filename: ')
        self.fileName = wxStaticText(self, -1, '')
        self.txt = wxStaticText(self, -1, 'Enter Key ')
        self.sndBtn = wxButton(self, -1, 'Insert')
        self.fileBtn = wxButton(self, -1, 'Select File')


#--------------------------------------------------------------------
# Leaving off the Cancel button until we're sure it works
#--------------------------------------------------------------------

        # self.termBtn = wxButton(self, -1, 'Cancel')

        self.inp.Enable(true)
        self.sndBtn.Enable(true)
        self.fileBtn.Enable(true)

        #self.termBtn.Enable(false)

        # Hook up the events
        EVT_BUTTON(self, self.sndBtn.GetId(), self.OnSendText)
        EVT_BUTTON(self, self.fileBtn.GetId(), self.OnFileSelect)
        #EVT_BUTTON(self, self.termBtn.GetId(), self.OnCloseStream)
        EVT_TEXT_ENTER(self, self.inp.GetId(), self.OnSendText)
        EVT_LIST_ITEM_SELECTED(self, listID, self.OnItemSelected)
        box3 = wxBoxSizer(wxHORIZONTAL)
        box3.Add(self.fileLabel, 0 , wxLEFT)
        box3.Add(self.fileName, 0 , wxLEFT)
        box4 = wxBoxSizer(wxHORIZONTAL)
        box4.Add(self.txt, 0, wxALIGN_CENTER)
        box4.Add(self.inp, 1, wxALIGN_CENTER)
        box4.Add(self.sndBtn, 0, wxLEFT, 10)
        box4.Add(self.fileBtn, 0, wxLEFT, 10)
        #box3.Add(self.termBtn, 0, wxLEFT, 5)

        #Put everything into a sizer

        sizer = wxBoxSizer(wxVERTICAL)
        sizer.Add(box1, 0, wxEXPAND|wxALL, 0)
        sizer.Add(self.out, 1, wxEXPAND|wxALL, 0)
        sizer.Add(box2, 1, wxEXPAND|wxALL, 0)
        sizer.Add(box3, 0, wxEXPAND|wxALL, 5)
        sizer.Add(box4, 0, wxEXPAND|wxALL, 5)

        self.SetSizer(sizer)
        self.SetAutoLayout(true)
        self.inp.SetFocus()

        self.timer = wxPyTimer(self.Pull)
        self.timer.Start(3000) #3 seconds
        self.Pull()

    def Pull(self):
        nbr = self.list.GetItemCount() - 1
        busy = 0
        while nbr > -1:
            item = self.list.GetItem(nbr, 2)
            col2 = item.GetText()
            if col2 == "Inserting":
                busy = 1
            nbr = nbr -1
        if busy != 1:
            nbr = self.list.GetItemCount() - 1
            while nbr > -1:
                item = self.list.GetItem(nbr, 2)
                col2 = item.GetText()
                if col2 == "Queued":
                    n = self.list.GetItemText(nbr)
                    self.inp.SetValue(n)
                    item = self.list.GetItem(nbr, 1)
                    f = item.GetText()
                    self.fileName.SetLabel(f)
                    self.list.DeleteItem(nbr)
                    self.OnForceText(self)
                    break
                nbr = nbr - 1

        #Check to see if there is any text output from download.py to display in out window
        if self.process is not None:
            stream = self.process.GetInputStream()
            if not stream.eof():
                text = stream.readline()
                while text:
                    text = stream.readline()
                    self.out.AppendText(text)


    def OnItemSelected(self, event):
        self.currentItem = event.m_itemIndex


    def OnRightDown(self, event):
        self.x = event.GetX()
        self.y = event.GetY()
        #self.log.add("x, y = %s\n" % str((self.x, self.y)))
        event.Skip()

    def OnRightClick(self, event):
        #self.log.add("OnRightClick %s\n" % self.list.GetItemText(self.currentItem))
        menu = wxMenu()
        tPopupID1 = 0
        menu.Append(tPopupID1, "Cancel")
        EVT_MENU(self, tPopupID1, self.OnPopupOne)
        self.PopupMenu(menu, wxPoint(self.x, self.y))
        menu.Destroy()
        event.Skip()

    def OnPopupOne(self, event):
        #self.log.add("Upload Cancel\n")
        pass

    def __del__(self):
        if self.process is not None:
            self.process.Detach()
            self.process.CloseOutput()
            self.process = None

    """
    def OnSendText(self, evt):
        cmd = "python upload.py"

        self.process = wxProcess(self)
        self.process.Redirect();

        pid = wxExecute(cmd, false, self.process)
        self.inp.SetFocus()
        self.log.add('Starting upload.py as pid %s\n' % (pid))

        keyname = self.inp.GetValue()
        keyname = "freenet:KSK@" + keyname

        hops = ("%s" % self.htl.GetValue())

        print keyname
        filename = self.fileName.GetLabel()
        print filename
        self.process.GetOutputStream().write(hops + '\n')
        self.process.GetOutputStream().write(keyname + '\n')
        self.process.GetOutputStream().write(filename + '\n')
        self.out.AppendText("Attempting to insert %s \n" % keyname)
        self.inp.SetFocus()
        #self.termBtn.Enable(true)
        pos=self.list.GetItemCount()
        self.list.InsertStringItem(pos, keyname)
        self.list.SetStringItem(pos, 1, "Inserting")

    def OnCloseStream(self, evt):
        print "onclosestream"
        self.process.CloseOutput()
        self.process = wxProcess(self)
        self.process.Redirect();
        pid = wxExecute(cmd, false, self.process)
        self.inp.SetFocus()
        self.log.add('OnCloseStream')
    """


    def OnSendText(self, evt):
        keyname = self.inp.GetValue()
        filename = self.fileName.GetLabel()
#        self.lblRequesting.SetLabel('Saving as: ')
        #If there are zero keys, start download right away, else mark Queued
        nbr = self.list.GetItemCount() - 1
        busy = 0
        while nbr > -1:
            item = self.list.GetItem(nbr, 2)
            col2 = item.GetText()
            nbr = nbr -1
            if col2 == "Inserting":
                busy = 1

        pos=self.list.GetItemCount()
        if busy == 0: # Not Inserting, so start insert, only one at a time though for now

            self.out.AppendText("Inserting key: \n %s \n\n" % keyname)
            self.out.AppendText("File: \n %s \n\n" % filename)

            self.list.InsertStringItem(0, keyname)  # Current downloads always go at top of list
            self.list.SetStringItem(0, 1, filename)
            self.list.SetStringItem(0, 2, "Inserting")

            cmd = ("python %s/upload.py" % snarfdir)
            self.process = wxProcess(self)
            self.process.Redirect();
            pid = wxExecute(cmd, false, self.process)
            #self.log.add('Starting upload.py as pid %s\n' % (pid))

            hops = self.htl.GetValue()
            keyindex = ('%s' %self.chkKeyIndex.GetValue())
            self.process.GetOutputStream().write(keyindex + '\n')
            self.process.GetOutputStream().write(hops + '\n')
            self.process.GetOutputStream().write(keyname + '\n')
            self.process.GetOutputStream().write(filename + '\n')

            self.inp.SetValue('')
            self.fileName.SetLabel('')
        else:
            if pos == 0:
                row = 0
            else:
                row = 1
            self.list.InsertStringItem(row, keyname)
            self.list.SetStringItem(row, 1, filename)
            self.list.SetStringItem(row, 2, "Queued")
            self.inp.SetValue('')
            self.fileName.SetLabel('')

    def OnForceText(self, evt):
        keyname = self.inp.GetValue()
        filename = self.fileName.GetLabel()
        #If there are zero keys, start download right away, else mark Queued
        pos=self.list.GetItemCount()
        # Always download from top (0) row
        self.list.InsertStringItem(0, keyname)
        self.list.SetStringItem(0, 1, filename)
        self.list.SetStringItem(0, 2, "Inserting")
        cmd = ("python %s/upload.py" % snarfdir)
        self.process = wxProcess(self)
        self.process.Redirect();
        pid = wxExecute(cmd, false, self.process)
        #self.log.add('Starting upload.py as pid %s\n' % (pid))
        hops = self.htl.GetValue()
        keyindex = ("%s" % self.chkKeyIndex.GetValue())
        self.process.GetOutputStream().write(keyindex + '\n')
        self.process.GetOutputStream().write(hops + '\n')
        self.process.GetOutputStream().write(keyname + '\n')
        self.process.GetOutputStream().write(filename + '\n')
        self.out.AppendText("Inserting key: \n %s \n\n" % keyname)
        self.out.AppendText("File: \n %s \n\n" % filename)
        self.inp.SetValue('')
        self.fileName.SetLabel('')

    def OnProcessEnded(self, evt):

        # There is something funky going on here. Hats off to whoever figures it out.
        # You can't send anything to other tabs -  self.log.add("foo") makes it hang
        #print "\n\nDONE\n\n"
        stream = self.process.GetInputStream()
        if not stream.eof():
            text = stream.read()
            self.process.Destroy()
            self.process = None

            self.out.AppendText(text)
            self.out.AppendText("\n")

            """
            if text[-1] == '*':
                failed = 1
            else:
                failed = 0
            if failed:
                status = "Done"
            else:
                status = "Done"
            try:
                a = os.stat("%s/download/%s" % (snarfdir, filename))
                f = a[6]
            except:
                f = 0
                if status != "Failed":
                    status = "Done"
            """


            keyname = self.list.GetItemText(0)
            item = self.list.GetItem(0, 1)
            filename = item.GetText()
            status = "Done."

            pos=self.list.GetItemCount() # Move to the bottom
            self.list.InsertStringItem(pos, keyname)
            self.list.SetStringItem(pos, 1, filename)
            self.list.SetStringItem(pos, 2, status)
            self.list.DeleteItem(0) # Delete top (Done)

            #filesize = ("%s" % f)
            #self.list.SetStringItem(nbr_items, 2, filesize)

    def OnFileSelect(self, event):
        dlg = wxFileDialog(self, "Choose a file", ".", "", "", wxOPEN|wxMULTIPLE)
        if dlg.ShowModal() == wxID_OK:
            for path in dlg.GetPaths():
                self.fileName.SetLabel(path)
                dlg.Destroy()

