#!/usr/bin/python
# coding=utf-8

import sys
from PyQt4 import QtGui, QtCore

import socket
import time
import threading
# import subprocess


import sys
from PyQt4 import QtGui, QtCore
from PyQt4.QtCore import Qt, SLOT, SIGNAL, QEventLoop, pyqtSlot
from PyQt4.QtGui import QDesktopWidget

from download import DownloadSoft  # 下载
from uiWindow.WaitingDialog import WaitingDialog
import os
from os import environ, getenv  # 环境变量


class UpgradeDownload(QtGui.QDialog):
    def __init__(self, url, parent=None):
        QtGui.QWidget.__init__(self)

        self.setWindowFlags(Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint)  # 无标题栏 | 置top
        self.setModal(True)
        screen = QDesktopWidget().screenGeometry()
        self.move((screen.width() - self.width()) / 2, (screen.height() - self.height()) / 2)
        self.__url = url  # 下载路径

        self.setGeometry(300, 300, 650, 150)
        self.setWindowTitle('下载更新')

        self.__waitingDlg = WaitingDialog()

        self.__eventloop = QEventLoop()
        self.__downloadStatus = False
        self.pbar = QtGui.QProgressBar(self)
        self.pbar.setGeometry(30, 60, 600, 25)

        self.lable = QtGui.QLabel("下载更新", self)
        # self.button_clean.setFocusPolicy(QtCore.Qt.NoFocus)

        self.connect(self, QtCore.SIGNAL("CLOSE"), self.close)
        self.timer = QtCore.QBasicTimer()
        self.step = 0

        self.downloadsolft = DownloadSoft(self.__url)

    def startDownload(self):
        self.onStart()
        # self.__waitingDlg.showFullScreen()
        self.__waitingDlg.showFullScreen_solfWareUpdate()

        self.downloadsolft.start_download_soft()  # 启动下载

    def timerEvent(self, event):  # 定时器 轮训下载进度

        self.step = self.step + 1
        downloadStep = self.downloadsolft.get_percentage()

        status = self.downloadsolft.checkDownloadState()
        # print "status == %s" % status

        if status == -1 or self.step > 10000: # 1000 毫秒
            # print "faile"
            self.emit(SIGNAL("DOWNLOAD_RESULT"),False)
        if status == 2:
            # print "---seccess  %s " % downloadStep
            self.emit(SIGNAL("DOWNLOAD_RESULT"),True)

        if self.step > 10000  or status == -1 or status == 2:
            self.timer.stop()
            self.__waitingDlg.close()
            self.close()

        msg = "正在下载 %s%% " % downloadStep
        self.__waitingDlg.showMsg(msg)
        self.pbar.setValue(downloadStep)

    def onStart(self):
        if self.timer.isActive():
            self.timer.stop()
        else:
            self.timer.start(100, self)

    def setClean(self):
        self.step = 0
        self.pbar.setValue(self.step)

    def download(self):

        # eventloop = QEventLoop()
        # self.connect(self, SIGNAL("DOWNLOAD_SECCESS"), self.__eventloop, SLOT("quit()"))
        # self.connect(self, SIGNAL("DOWNLOAD_FAILE"), self.__eventloop, SLOT("quit()"))
        self.connect(self, SIGNAL("DOWNLOAD_RESULT"), self.downloadResult)
        self.startDownload()
        self.__eventloop.exec_()
        print "over"
        return self.__downloadStatus

    @pyqtSlot()
    def downloadResult(self,flag):
        print "downLoadResult : "  ,flag
        self.__downloadStatus = flag
        self.__eventloop.quit()

if __name__ == "__main__":
    from PyQt4.QtCore import QTextCodec
    # import sys
    # sys.setdefaultencoding('utf-8')

    QTextCodec.setCodecForCStrings(QTextCodec.codecForLocale())  # 支持中文
    app = QtGui.QApplication(sys.argv)
    environ["WIN_UI_IMAGES_PATH"] = "../../../images"  # 图片路径

    icon = UpgradeDownload("http://192.168.1.62:8008/mcos-linux-client_201605271033.deb1")
    # icon.startDownload()
    if icon.download():
        print "下载成功"
    else:
        print "下载失败"

    # sys.exit(app.exec_())
