#!/usr/bin/env python
# -*- coding: utf-8 -*-
# generated by wxGlade 0.6.3 on Sun Jul 08 15:59:49 2012

import wx
import wx.lib.newevent
import fileDownloader
import urlparse
import sys
import os
import thread
import traceback
import urllib
import platform
import os

# begin wxGlade: extracode
# end wxGlade

(DownloadReport,EVT_DRA)=wx.lib.newevent.NewEvent()

MYOS = platform.system()
def cur_file_dir():
    #获取脚本路径
    global MYOS
    if MYOS == 'Linux':
        path = sys.path[0]
    elif MYOS == 'Windows':
        return os.path.dirname(os.path.abspath(sys.argv[0]))
    else:
        if sys.argv[0].find('/') != -1:
            path = sys.argv[0]
        else:
            path = sys.path[0]
    if isinstance(path,str):
        path=path.decode('utf-8')

    #判断为脚本文件还是py2exe编译后的文件，如果是脚本文件，则返回的是脚本的目录，如果是编译后的文件，则返回的是编译后的文件路径
    if os.path.isdir(path):
        return path
    elif os.path.isfile(path):
        return os.path.dirname(path)


def HumanSize(ffsize):
    fsize=float(ffsize)
    if fsize >= 1000000000.0:
        r=float(fsize)/1000000000.0
        return '%(#).2f' % {'#':r}+' GB'
    else:
        if fsize>=1000000:
            r=float(fsize)/1000000.0
            return '%(#).2f' % {'#':r}+' MB'
        else:
            if fsize>=1000:
                r=float(fsize)/1000.0
                return '%(#).2f' % {'#':r}+' KB'
            else:
                return '< 1KB'

class DownloadManager(wx.Frame):
    def __init__(self,parent,savepath='.'):
        """
        savepath is the directory save the download file
        """
        # begin wxGlade: DownloadManager.__init__
        #kwds["style"] = wx.DEFAULT_FRAME_STYLE
        wx.Frame.__init__(self, parent,-1)
        self.sizer_4_staticbox = wx.StaticBox(self, -1, "")
        self.sizer_3_staticbox = wx.StaticBox(self, -1, u"当前任务")
        self.list_ctrl_1 = wx.ListCtrl(self, -1, style=wx.LC_REPORT|wx.SUNKEN_BORDER)
        self.button_8 = wx.Button(self, -1, u"添加")
        self.button_9 = wx.Button(self, -1, u"删除")
        self.button_10 = wx.Button(self, -1, u"继续下载")
        self.button_11 = wx.Button(self, -1, u"暂停")
        self.tasklist = {}
        self.savepath=savepath

        self.Bind(EVT_DRA,self.updateProgress)
        self.Bind(wx.EVT_BUTTON, self.resumeDownloading, self.button_10)
        self.Bind(wx.EVT_BUTTON, self.stopDownloading, self.button_11)
        self.Bind(wx.EVT_BUTTON, self.delTask, self.button_9)
        self.Bind(wx.EVT_BUTTON, self.inputURL, self.button_8)
        self.Bind(wx.EVT_CLOSE,self.OnClose)
        self.list_ctrl_1.Bind(wx.EVT_LIST_ITEM_SELECTED,self.onSelect)

        self.__set_properties()
        self.__do_layout()
        # end wxGlade

    def __set_properties(self):
        # begin wxGlade: DownloadManager.__set_properties
        _icon = wx.EmptyIcon()
        _icon.CopyFromBitmap(wx.Bitmap(cur_file_dir()+u"/icon/litebook-icon_32x32.png", wx.BITMAP_TYPE_ANY))
        self.SetIcon(_icon)
        self.SetTitle(u"下载管理器")
        self.SetBackgroundColour(wx.SystemSettings_GetColour(wx.SYS_COLOUR_WINDOW))
        self.list_ctrl_1.InsertColumn(0,u'文件名',width=200)
        self.list_ctrl_1.InsertColumn(1,u'URL',width=300)
        self.list_ctrl_1.InsertColumn(2,u'进度')
        self.list_ctrl_1.InsertColumn(3,u'大小')
        self.SetSize((700,400))


        # end wxGlade

    def __do_layout(self):
        # begin wxGlade: DownloadManager.__do_layout

        sizer_2 = wx.BoxSizer(wx.VERTICAL)
        sizer_4 = wx.StaticBoxSizer(self.sizer_4_staticbox, wx.HORIZONTAL)
        sizer_3 = wx.StaticBoxSizer(self.sizer_3_staticbox, wx.HORIZONTAL)
        sizer_3.Add(self.list_ctrl_1, 1, wx.EXPAND, 0)
        sizer_2.Add(sizer_3, 1, wx.EXPAND, 0)
        sizer_4.Add((20, 20), 1, 0, 0)
        sizer_4.Add(self.button_8, 0, 0, 0)
        sizer_4.Add((20, 20), 0, 0, 0)
        sizer_4.Add(self.button_9, 0, 0, 0)
        sizer_4.Add((20, 20), 0, 0, 0)
        sizer_4.Add(self.button_10, 0, 0, 0)
        sizer_4.Add((20, 20), 0, 0, 0)
        sizer_4.Add(self.button_11, 0, 0, 0)
        sizer_4.Add((20, 20), 1, 0, 0)
        sizer_2.Add(sizer_4, 0, wx.EXPAND|wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL, 0)
        self.SetSizer(sizer_2)
        #sizer_2.Fit(self)
        self.Layout()
        # end wxGlade


    def addTask(self,url,savepath=None):
        """
        return False if invalid url
        """
        newurl=url
        if newurl[:7].lower() != 'http://':
            newurl='http://'+newurl
        purl=urlparse.urlparse(newurl)
        if purl.netloc=='' or purl.scheme <>'http' or purl.path == '':
            return False
        for t in self.tasklist.values():
            if t['url'] == newurl: return
        if savepath==None:
            savepath=self.savepath
        fname = str(os.path.basename(urlparse.urlparse(newurl).path))
        fname = urllib.unquote_plus(fname).decode('utf-8')
        ti=self.list_ctrl_1.InsertStringItem(sys.maxint,fname)

        self.list_ctrl_1.SetItemData(ti,ti)
        self.list_ctrl_1.SetStringItem(ti,1,newurl)#url
        self.list_ctrl_1.SetStringItem(ti,2,u'开始下载')#cur
        self.list_ctrl_1.SetStringItem(ti,3,'0')#total
        localname=os.path.abspath(savepath+os.sep+fname)
        dt=DThread(self,newurl,ti,localname)
##        print "add ",newurl,"as ",ti
        self.tasklist[ti]={'url':newurl,'thread':dt,'localname':localname}
        return True

    def updateProgress(self,evt):
        if evt.current_size == False or evt.total_size == False:
            self.list_ctrl_1.SetStringItem(evt.tid,2,u'失败')
            self.list_ctrl_1.SetStringItem(evt.tid,3,u'失败')
            self.Refresh()
            return

        if evt.current_size==-1:
            self.list_ctrl_1.SetStringItem(evt.tid,2,u'完成')
            self.updateButtonStatus()
        else:
            self.list_ctrl_1.SetStringItem(evt.tid,2,HumanSize(evt.current_size))
        self.list_ctrl_1.SetStringItem(evt.tid,3,HumanSize(evt.total_size))
        self.Refresh()

    def resumeDownloading(self,evt):
        item=-1
        while True:
            item=self.list_ctrl_1.GetNextSelected(item)
            if item == -1: return
            dt=DThread(self,self.tasklist[item]['url'],item,self.tasklist[item]['localname'])
            self.tasklist[item]['thread']=dt
            if self.list_ctrl_1.GetItem(item,2).GetText()!=u'失败':
                self.button_10.Disable()
                self.button_11.Enable()
            self.list_ctrl_1.SetStringItem(item,2,u'开始下载')#cur
            self.list_ctrl_1.SetStringItem(item,3,u'0')#total




    def stopDownloading(self,evt):
        item=-1
        while True:
            item=self.list_ctrl_1.GetNextSelected(item)
            if item == -1: return
            self.tasklist[item]['thread'].stop()
            self.button_11.Disable()
            if self.list_ctrl_1.GetItem(item,2).GetText()==u'完成':
                self.button_10.Disable()
            else:
                self.button_10.Enable()

    def updateButtonStatus(self):
        selected_item=self.list_ctrl_1.GetNextSelected(-1)
        if selected_item == -1:return
        task_id=self.list_ctrl_1.GetItemData(selected_item)
        if self.tasklist[task_id]['thread'].running == True:
            self.button_10.Disable()
            self.button_11.Enable()
        else:
            self.button_11.Disable()
            if self.list_ctrl_1.GetItem(selected_item,2).GetText()==u'完成':
                self.button_10.Disable()
            else:
                self.button_10.Enable()
        self.Refresh()
        self.Update()


    def printlist(self):
        i=-1
        print "*******************"
        while True:
            i=self.list_ctrl_1.GetNextSelected(i)
            if i==-1:return
            print i,'----',self.list_ctrl_1.GetItemData(i)

    def _delItemviaData(self,data):
        i=-1
        while True:
            i=self.list_ctrl_1.GetNextItem(i)
            if i==-1: return False
            if self.list_ctrl_1.GetItemData(i)==data:
                self.list_ctrl_1.DeleteItem(i)
                return i




    def delTask(self,evt):
        item=-1
        s_list=[]
        while True:
            item=self.list_ctrl_1.GetNextSelected(item)
            if item == -1: break
            else:
                s_list.append(item)
        for data in s_list:
            self.tasklist[data]['thread'].stop()
            self._delItemviaData(data)

##            self.button_11.Disable()
##            if self.list_ctrl_1.GetItem(item,2).GetText()==u'完成':
##                self.button_10.Disable()
##            else:
##                self.button_10.Enable()


    def inputURL(self,evt):
        dlg = wx.TextEntryDialog(
                self, u'请输入地址：',
                u'添加下载任务', '')

        if dlg.ShowModal() == wx.ID_OK:
            if self.addTask(dlg.GetValue()) == False:
                mdlg = wx.MessageDialog(self,u'错误的HTTP URL!',
                   u'出错了！',
                   wx.OK | wx.ICON_ERROR
                   )
                mdlg.ShowModal()
                mdlg.Destroy()
        dlg.Destroy()


    def onSelect(self,evt):
        self.updateButtonStatus()

    def OnClose(self,evt):
        self.Hide()
# end of class DownloadManager

class DThread:
    def __init__(self,win,url,id,savename):
        self.win=win
        self.url=url
        self.tid = id
        self.savename=savename
        self.running=False
        thread.start_new_thread(self.run, ())


    def report(self,cur,all):
        """
        report download progress via wx.PostEvent
        """
        new_evt=DownloadReport(current_size=cur,total_size=all,tid=self.tid)
        wx.PostEvent(self.win,new_evt)


    def run(self):
        self.running=True
        self.downloader=fileDownloader.DownloadFile(self.url,localFileName=self.savename)
        if self.running == False: return
        try:
            if os.path.isfile(self.savename):
                self.downloader.resume(reportFunc=self.report)
            else:
                self.downloader.download(reportFunc=self.report)
        except Exception as inst:
            print traceback.format_exc()
            print inst
        self.running=False


    def stop(self):
        try:
            self.downloader.stop()
        except:
            pass
        self.running=False




if __name__ == "__main__":
    app = wx.PySimpleApp(0)
    wx.InitAllImageHandlers()
    frame_1 = DownloadManager(None)
    #frame_1.addTask('http://litebook-project.googlecode.com/files/LiteBook2_v2d.1_Win_setup.exe','.')
    #frame_1.addTask('http://127.0.0.1:8000/%E5%86%92%E7%89%8C%E5%A4%A7%E8%8B%B1%E9%9B%84.epub','.')
    frame_1.addTask('http://10.10.10.10:8000/1.epub','.')
    frame_1.addTask('http://20.20.20.20:8000/2.epub','.')
    frame_1.addTask('http://30.30.30.30:8000/3.epub','.')
    app.SetTopWindow(frame_1)
    frame_1.Show()
    app.MainLoop()
