from wxPython.wx import *
import os, sys, threading, time
from xrflib import getKey
from prefs import *

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

'''
TODO: Use a wxSplitter
      GnuPG/PGP Encryption/signing
'''

class panelfmail(wxPanel):
    """
    This class starts a getKey thread to download a IndexClient key.

    """

    def __init__(self, parent):
        wxPanel.__init__(self, parent, -1)
        self.que = {} # Dictionary to hold row information with keys, status, filesize etc.
        #----------------------------------------------------------------------------------
        # Options at top (Box 1)
        #----------------------------------------------------------------------------------
        htlid = wxNewId()
        spinId = wxNewId()
        box1 = wxBoxSizer(wxHORIZONTAL)

        self.lblhtl= wxStaticText(self, -1, " Hops to Live: ")
        self.htl = wxTextCtrl(self, htlid, '50', wxDLG_PNT(self, 10, 10), wxDLG_SZE(self, 15, 12)) #, wxSize(30, 20)
        self.htl.Enable(true)
        self.spin = wxSpinButton(self, spinId, wxPoint(20,20), wxSize(20,20), wxSP_VERTICAL)
        self.spin.SetRange(1, 200)
        self.spin.SetValue(50)
        EVT_SPIN(self, spinId, self.OnSpin)
        box1.Add(self.lblhtl, 0, wxRIGHT)
        box1.Add(self.htl, 0, wxRIGHT)
        box1.Add(self.spin, 0, wxRIGHT)

        listID = wxNewId()
        self.list= wxListCtrl(self, listID, size=wxDefaultSize,style=wxLC_REPORT|wxSUNKEN_BORDER)
        self.list.InsertColumn(0,"Box (Index)")
        self.list.InsertColumn(1,"Nbr")
        self.list.InsertColumn(2,"Date")
        self.list.InsertColumn(3,"Subject")
        self.list.InsertColumn(4,"Size")
        self.list.InsertColumn(5,"Status")
        self.list.InsertColumn(6,"Key / Filename")
        self.list.SetColumnWidth(0, 120)
        self.list.SetColumnWidth(1, 40)
        self.list.SetColumnWidth(2, 90)
        self.list.SetColumnWidth(3, 350)
        self.list.SetColumnWidth(4, 100)
        self.list.SetColumnWidth(5, 70)
        self.list.SetColumnWidth(6, 230)
        box2 = wxBoxSizer(wxHORIZONTAL)
        box2.Add(self.list, 1, wxEXPAND|wxALL,0)

        self.message = wxTextCtrl(self, -1, '', style=wxTE_MULTILINE|wxTE_READONLY)
        box3 = wxBoxSizer(wxHORIZONTAL)
        box3.Add(self.message, 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)

        # Hook up the events
        EVT_LIST_ITEM_SELECTED(self, listID, self.OnItemSelected)
        sizer = wxBoxSizer(wxVERTICAL)
        sizer.Add(box1, 0, wxEXPAND|wxALL, 0) #wxEXPAND|wxALL
        sizer.Add(box2, 1, wxEXPAND|wxALL, 0)
        sizer.Add(box3, 1, wxEXPAND|wxALL, 0)
        self.SetSizer(sizer)
        self.SetAutoLayout(true)


    def OnSpin(self, event):
        self.htl.SetValue(str(event.GetPosition()))

    def OnItemSelected(self, event):
        self.currentItem = event.m_itemIndex
        #filename = self.list.GetItemText(self.currentItem)
        item = self.list.GetItem(self.currentItem, 6)
        filename = item.GetText()
        item = self.list.GetItem(self.currentItem, 5)
        status = item.GetText()
        if status == 'Queued':
            self.message.Clear()
        else:
            filename = ('%s/fmail/%s' % (snarfdir, filename))
            f = open(filename, 'r')
            txt = f.read()
            msg = ('%s' % txt)
            self.message.Clear()
            self.message.AppendText(msg)
            #win32
            #self.list.SetStringItem(self.currentItem, 4, '')
            item = self.list.GetItem(self.currentItem)
            item.SetTextColour(wxBLACK)
            self.list.SetItem(item)

    def OnRightDown(self, event):
        self.x = event.GetX()
        self.y = event.GetY()
        event.Skip()

    def OnRightClick(self, event):
        # if Debug:
        #print self.list.GetItemText(self.currentItem)
        #print "Length:"
        #print len(self.list.GetItemText(self.currentItem))
        menu = wxMenu()
        openId = wxNewId()
        replyId = wxNewId()
        menu.Append(replyId, 'Reply')
        menu.Append(openId, 'Open')
        EVT_MENU(self, openId, self.OnLaunch)
        EVT_MENU(self, replyId, self.OnReply)
        self.PopupMenu(menu, wxPoint(self.x, self.y))
        menu.Destroy()
        event.Skip()
    '''
    def CountBusy(self):
        row = 0
        while 1:
            item = self.list.GetItem(row, 4)
            row = row + 1
            nbrRows = self.list.GetItemCount()
            if row > nbrRows:
                break
    '''

    def CountItems(self):
        nbr = self.list.GetItemCount()
        return nbr

    def OnReply(self, event):
        pass

    def OnForceDownload(self, event):
        nbr = self.list.GetItemCount() - 1
        busy = 0
        while nbr > -1:
            item = self.list.GetItem(nbr, 1)
            col1 = item.GetText()
            nbr = nbr -1
        n = self.list.GetItemText(self.currentItem)
        i = self.currentItem
        self.list.DeleteItem(i) #Delete the item we're on because it gets added again in OnSendText
        self.OnSendText(self) # Send to download tab, start downloading or be queued

    def OnLaunch(self, event):
        item = self.list.GetItem(self.currentItem, 6)
        filename = item.GetText()
        try:
            os.system("%s %s%sfmail%s%s &" % (helper, snarfdir, os.sep, os.sep, filename))
        except:
            if debug == '1':
                print sys.exc_type, sys.exc_value
            #msg = ("Can't open file %s\n Check your 'Helper App' setting in 'Snarfzilla Preferences'" % filename)
            #win32
            msg = ("Not implemented in Windows")
            dlg = wxMessageDialog(self, msg, 'Error opening file',
            wxOK | wxICON_INFORMATION)
            dlg.ShowModal()
            dlg.Destroy()


    def Checking(self, keyname):
        row = 0
        alreadyChecking = 0
        if self.CountItems():
            while 1:
                item = self.list.GetItem(row, 6)
                thiskey = item.GetText()
                if thiskey == keyname:
                    alreadyChecking = 1
                    break
                row = row + 1
                if row > self.CountItems():
                    break
            return alreadyChecking

    def BreakUpKey(self, keyname):
        nbrDashes = string.count(keyname, '-')
        fields = string.splitfields(keyname, '-', nbrDashes)
        indexNbr = fields[nbrDashes]
        if  nbrDashes == 4:
            index = ('%s-%s-%' % (fields[0], fields[1], fields[2]))
        if  nbrDashes == 3:
            index = ('%s-%s' % (fields[0], fields[1]))
        if  nbrDashes == 2:
            index = fields[0]
        keyParts = {}
        keyParts[0] = index
        keyParts[1] = fields[nbrDashes - 1] # Date
        keyParts[2] = fields[nbrDashes] # Index nbr
        return keyParts

    def AddKeyToRow(self, keyname, status ):
        keyParts = self.BreakUpKey(keyname)
        index = keyParts[0]
        midnight = keyParts[1]
        indexNbr = keyParts[2]
        timetuple = time.gmtime(string.atoi(midnight))
        date = time.strftime(" %d %b %Y", timetuple)

        #doing = self.Checking(keyname)
        doing = 0
        if not doing:
            keyname = string.strip(keyname)
            keyname = (r'%s' % keyname)
            f = string.replace(keyname, '\\', '/')
            f = string.replace(f, '@', '/')
            if string.find(f, '/') != -1:
                dirname, filename = os.path.split(f)
            else:
                filename = keyname # plain kay like 'test'
            row = 0
            self.list.InsertStringItem(row, index)
            self.list.SetStringItem(row, 1, indexNbr)
            self.list.SetStringItem(row, 2, date)
            self.list.SetStringItem(row, 3, "")
            if os.path.exists('/snarfzilla/fmail/%s' % (filename)):
                size = '%s' % os.stat('/snarfzilla/fmail/%s' % (filename))[6]
            else:
                size = ''
            self.list.SetStringItem(row, 4, size)
            self.list.SetStringItem(row, 5, status)
            self.list.SetStringItem(row, 6, keyname)
            if status != "Old":
                hops = self.htl.GetValue()
                server = '127.0.0.1'
                port = 6690
                dir = 'fmail'
                xrf = getKey(self, server, port, keyname, filename, hops, dir)
                try:
                    xrf.start()
                except:
                    print 'Error with XML-RPC transfer!\n'
        self.list.Refresh()
            #nbrRows = len(self.que)

    def UpdateRow(self, keyname, status, filesize, ttlFileSize):
        if ttlFileSize == -1: #Fail
            size = ''
            status = 'Failed'
        #else:
        row = 0
        #print 'status', status
        while 1:
            item = self.list.GetItem(row, 6)
            thiskey = item.GetText()

            if thiskey == keyname:
                if status == 'Failed':
                    self.list.DeleteItem(row)
                    break
                else:
                    status = 'New'
                    self.que[keyname] = [status, filesize]
                    self.list.SetStringItem(row, 3, '(None)')
                    #self.list.SetStringItem(row, 4, size)
                    self.list.SetStringItem(row, 5, status)
                    self.list.SetStringItem(row, 6, keyname)
                    item = self.list.GetItem(row)
                    #win32
                    #item.SetTextColour(wxBLUE)
                    self.list.SetItem(item)
                    break
            row = row + 1
            nbrRows = self.list.GetItemCount()
            if row > nbrRows:
                break
        self.list.Refresh()
        #print threading.enumerate()
