# -*- coding: UTF-8 -*-

#from xml.dom.minidom import Document
from PCont import PCont
from xmlrpclib import Server
import cPickle
import os, sys, string
from stat import *
import pycurl
import thread
import sha
import time
from wxPython.wx import *
from wxPython.gizmos import *
from wxPython.lib.buttons import *
from urllib import quote


class prepareEvent(wxPyEvent):

    def __init__(self,evt):
        wxPyEvent.__init__(self)
        self.SetEventType(evt)

class checker:

    def __init__(self):
        self.contents = ''


    def bodyc(self,buf):
        self.contents = self.contents + buf


    def checkfile(self,h,u,p,f):
        contents = ''
        c = pycurl.Curl()
        c.setopt (c.URL, str('http://protor:test12@%s/putperl?filename=%s' % (h,quote(f))))
#        c.setopt(c.VERBOSE, 1)
        c.setopt(c.WRITEFUNCTION, self.bodyc)
        c.perform()
        len = 0
        sum = 0

        if (string.find(self.contents,'file=') > -1)\
            and (string.find(self.contents,':ok') > -1):
            t = self.contents.split(':')

            file = t[0].split("="); file = file[1]
            len = t[1].split("="); len = int(len[1]);
            sum = t[2].split("="); sum = sum[1];

            ret = 'append'
        else:
           if string.find(self.contents,'401 Authorization Required') > -1:
               ret = '401'
           else:
               ret = 'new'

        c.close()
        return(ret,len,sum)




class upload:

    def __init__(self,gui):
        self.gui = gui
        self.c = 1
        self.id = ''
        self.upload_t = 1
        self.upload_d = 1
        pass


    def getText(self,nodelist):
        rc = ""
        for node in nodelist:
            if node.nodeType == node.TEXT_NODE:
                rc = rc + node.data
        return rc


    def collectData(self,tag):
        try:
            creator = self.doc.getElementsByTagName(tag)[0]
            return self.getText(creator.childNodes)
        except:
            return "empty"


    def loadData(self,file):
        FILE = open(file, 'r')
        self.pcont = cPickle.load(FILE)
        self.doc = self.pcont.doc
        FILE.close()
        self.id = self.collectData("dc:identifier")


    def progress(self, download_t, download_d, upload_t, upload_d):
        self.c = self.c + 1
        self.upload_t = upload_t
        self.upload_d = upload_d
        evt = prepareEvent(self.gui.wxEVT_UPDATE_PROGRESS)
        wxPostEvent(self.gui,evt)


    def sha1sum(self,filename):
        file = open(filename,"rb")
        h = sha.new()
        while 1:
            data = file.read(4096)
            if data == "":
                break
            h.update(data)
        file.close()
        return(h.hexdigest())


    def uploadData(self,pathname):
        self.c = 1
        rcmd=''

        name = self.id

        print "the NAME: %s, the FILE: %s" % (name,self.pcont.filename)

        check = checker()
        nxt,rlen,rsum =  check.checkfile(self.gui.servername.GetValue(),\
            self.gui.username.GetValue(), self.gui.password.GetValue(), name)
        lsum = self.sha1sum(self.pcont.filename)
        file = open(self.pcont.filename,"rb")
        llen = os.stat(self.pcont.filename)[6]

        if(nxt == "401"):
            self.gui.errDialog('Username or Password incorrect')
            return
        else:
            if(nxt == 'new'):
                rcmd = 'new'
            elif(llen > rlen):
                rcmd = 'append'
            elif(llen < rlen):
                rcmd = 'new'
            elif((llen == rlen) and (rsum == lsum)):
                serv = Server("http://archive.reboot.fm:9500/")
                if(os.name == "nt"):
                     n = serv.oma.receive_dc_set(self.doc.toxml(),
                         self.gui.username.GetValue())
                else:
                    n = serv.oma.receive_dc_set(unicode(self.doc.toxml(),'latin-1'),
                         self.gui.username.GetValue())
                    #n = serv.oma.receive_dc_set(unicode(self.doc.toxml(),'latin-1'),
                    #   self.gui.username.GetValue())
                    
                os.remove(pathname)
                time.sleep(1)
                return
            
            if(len(rcmd)>0):
                self.curl = pycurl.Curl();
                u = string.replace(self.gui.username.GetValue(),'@','%40');
                self.curl.setopt(self.curl.URL, str('http://protor:test12@%s/putperl' % \
                    ( self.gui.servername.GetValue())))

            
                self.curl.setopt(self.curl.VERBOSE, 0)
                self.curl.setopt(self.curl.COOKIE, str("filename=%s;cmd=%s" % (quote(name),rcmd)))
                self.curl.setopt(self.curl.UPLOAD, 1)
                self.curl.setopt(self.curl.PUT, 1)
                self.curl.setopt(self.curl.NOPROGRESS, 0)
                self.curl.setopt(self.curl.READDATA, file)
                self.curl.setopt(self.curl.INFILESIZE, int(llen))
                self.curl.setopt(self.curl.PROGRESSFUNCTION, self.progress)

                if(rcmd == 'append'):
                    self.curl.setopt(self.curl.CURLOPT_RESUME_FROM, rlen)

                try:
                    self.curl.perform()
                    self.curl.close()
                except:
                    import traceback
                    traceback.print_exc()

        self.c=0
        evt = prepareEvent(self.gui.wxEVT_UPDATE_PROGRESS)
        wxPostEvent(self.gui,evt)

    def startque(self):
        cwd = os.getcwd()
        while 1:
            self.inQueue = []
            if (os.getcwd() == cwd):

                for f in os.listdir('./spool'):
                    pathname = './spool/%s' %  f
                    mode = os.stat(pathname)[ST_MODE]
                    if S_ISREG(mode):
                        # It's a file, call the callback function
                        if string.find(pathname,'jobs'):
                            self.loadData(pathname)
                            self.inQueue.append(self.collectData("dc:identifier"))

                for f in os.listdir('./spool'):
                    pathname = './spool/%s' %  f
                    mode = os.stat(pathname)[ST_MODE]
                    if S_ISREG(mode):
                        # It's a file, call the callback function
                        if string.find(pathname,'jobs'):
                            self.loadData(pathname)
                            self.uploadData(pathname)
                            time.sleep(1)
#                            self.uploadData(pathname)
#                            time.sleep(1)

            time.sleep(5)
            evt = prepareEvent(self.gui.wxEVT_UPDATE_PROGRESS)
            wxPostEvent(self.gui,evt)
