#!/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()
#(DownloadUpdateAlert,EVT_DUA)=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 WebDownloadManager(wx.Frame):
    def __init__(self,parent):
        """
        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.btn_del = wx.Button(self,wx.ID_DELETE,label=u'删除')
        self.btn_cancel = wx.Button(self,wx.ID_CANCEL,label=u'取消')
        self.tasklist = {}


##
##        self.Bind(EVT_DRA,self.updateProgress)
        self.Bind(wx.EVT_BUTTON, self.onClose, self.btn_cancel)
        self.Bind(wx.EVT_BUTTON, self.onDel, self.btn_del)
##        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"WEB下载管理器")
        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'网址',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.btn_del, 0,0, 0)
        sizer_4.Add((20, 20), 0,0, 0)
        sizer_4.Add(self.btn_cancel, 0,0, 0)
        sizer_2.Add(sizer_4, 0, wx.EXPAND|wx.ALIGN_CENTER_VERTICAL, 5)
        self.SetSizer(sizer_2)
        #sizer_2.Fit(self)
        self.Layout()
        # end wxGlade


    def addTask(self,task):
        ti=self.list_ctrl_1.InsertStringItem(sys.maxint,task['bkname'])
        #self.list_ctrl_1.SetItemData(ti,task['url'])
        self.list_ctrl_1.SetStringItem(ti,1,task['url'])
        self.list_ctrl_1.SetStringItem(ti,2,u'开始下载...')
        self.list_ctrl_1.SetStringItem(ti,3,task['size'])
        self.tasklist[task['url']]=[]

    def findItem(self,url):
        i=-1
        while True:
            i=self.list_ctrl_1.GetNextItem(i)
            if i==-1: return -1
            if self.list_ctrl_1.GetItem(i,1).GetText()==url:
                return i

    def updateProgress(self,msg,url):
        item=self.findItem(url)
        if item == -1:
            return
        self.list_ctrl_1.SetStringItem(item,2,msg)



    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 onDel(self,evt):
        item=-1
        item_list=[]
        while True:
            item=self.list_ctrl_1.GetNextSelected(item)
            if item == -1: break
            item_list.append(item)
        self.delTask(item_list)


    def delTask(self,item_list):
        for item in item_list:
            url=self.list_ctrl_1.GetItem(item,1).GetText()
            self.tasklist[url].append(False)
            break
        self.list_ctrl_1.DeleteItem(item)




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




if __name__ == "__main__":
    app = wx.PySimpleApp(0)
    wx.InitAllImageHandlers()
    frame_1 = WebDownloadManager(None)
    app.SetTopWindow(frame_1)
    frame_1.Show()
    app.MainLoop()
