#!/usr/bin/env python
# coding=utf-8
import os

from PyQt4.QtCore import SIGNAL, QUrl, QFile, QIODevice, QObject, QEventLoop, SLOT
from PyQt4.QtGui import QApplication
from PyQt4.QtNetwork import QNetworkAccessManager, QNetworkRequest, QNetworkReply

class DownloadSoft(QObject):
    def __init__(self, url,parent=None):
        super(DownloadSoft, self).__init__(parent)
        self.__url=url
        self.soft_name = ""
        self.sendbyte = 0
        self.totlabyte = 0
        self.soft_info_list = None
        self.__downloadState = 0

    def checkDownloadState(self):# 0 未下载   1 下载中   2 下载完成  -1 下载失败
        return self.__downloadState

    def get_percentage(self):    #获取下载进度（%）的方法
        if self.sendbyte == 0 or self.totlabyte == 0:
            return -1
        return self.sendbyte * 100 / self.totlabyte

    def start_download_soft(self):
        self.__downloadState = 0
        self.downLoadd_soft()

    def downLoadd_soft(self):
        retu = self.download_fun()
        print "THIS IS INSTALL SOFT RETU",retu

    def download_tmp(self, url_file_path):#下载函数
        try:
            url_file_path_split = url_file_path.split("/")
            tmp_file =  url_file_path_split[len(url_file_path_split) - 1]#get file name
            self.url = QUrl(url_file_path)
            self.fileInfo = self.url.path()
            # self.file = QFile("/tmp/"+ tmp_file)
            self.file = QFile("/tmp/mcos-linux-client.deb")
            self.file.open(QIODevice.WriteOnly)
            self.acceddManager = QNetworkAccessManager(self)
            self.request = QNetworkRequest()
            self.request.setUrl(self.url)
            self.reply = QNetworkReply
            self.reply = self.acceddManager.get(self.request)
            self.connect(self.acceddManager, SIGNAL("finished(QNetworkReply*)"), self.replyFinished)
            self.connect(self.reply, SIGNAL("downloadProgress(qint64,qint64)"), self.onDownloadProgress)
            self.connect(self.reply, SIGNAL("readyRead()"), self.onReadyRead)
        except Exception as e:
            print e.message,"this is e.message ."

    def onReadyRead(self):
        self.file.write(self.reply.readAll())

    def onDownloadProgress(self, pro, total):
        self.__downloadState = 1
        self.sendbyte = pro
        self.totlabyte = total

    def replyFinished(self, reply):
        if (reply.error() == QNetworkReply.NoError):
            self.__downloadState = 2
            print "download succeed "#成功下载完成后提示
        else:
            self.__downloadState = -1
            print "download error"#下载过程中出现错误提示
        self.file.close()
        self.emit(SIGNAL("replyFinished"))
        reply.deleteLater()

    def download_fun(self):
        self.emit(SIGNAL("download_start"), 'start')
        try:
            url_file_path_list = []
            # url_file_path_list.append(str("http://192.168.7.146:8008/SYSTEM_ISO/WIN03PE.iso"))
            url_file_path_list.append(str(self.__url))
            for i in range(len(url_file_path_list)):
                _eventloop = QEventLoop()
                self.connect(self,SIGNAL("replyFinished"),_eventloop,SLOT("quit()"))
                self.download_tmp(url_file_path_list[i])
                _eventloop.exec_()
        except Exception as e:
            print e.message,"this is e.message"
            self.emit(SIGNAL("download_error"), "error")
        self.emit(SIGNAL("download_over"), 'over')

if __name__ == "__main__":

    from time import sleep
    app = QApplication([])
    _DownloadSoft = DownloadSoft()
    _DownloadSoft.start_download_soft()
    while True:
        sleep(1) 
        i =  _DownloadSoft.get_percentage()
        print i
#        if i=
    app.exec_()

