class UploadThread(QtCore.QThread):
    def __init__(self, file_path, upload_folder_id=None):
        super(UploadThread, self).__init__()
        # ::type: TabDownloadController
        # threadID = filepath
        # phai truyen mainwindows.
        self.file_path = file_path
        self.storagonSDK = StoragonSDK()
        # can upload vao folder nao thi cho vao

        self.upload_folder_id = upload_folder_id
        self.uploaded_file_id = 0
        self.pausenow = False

    def run(self):
        # self.checkAndWait()
        print(u"Upload thread start to upload %s" % self.file_path)
        # self.uploadController.setStatusBar('Uploading...')
        self.storagonSDK.uploadFile(self.file_path, self.upload_folder_id, self.progressFunction)

    def checkAndWait(self):
        while True:
            if self.pausenow:
                time.sleep(0.5)
            else:
                break

    def progressFunction(self, download_t, download_d, upload_t, upload_d, speed=None):
        """

        :param download_t: uploaded file_id
        :param download_d: 0
        :param upload_t: file_size
        :param upload_d: uploaded size
        :return:
        """
        self.checkAndWait()
        # self.checkStop()
        # print download_t,download_d,upload_t,upload_d

        # self.downloadController.updateStatus(self.link,'Ready for download',file_size=download_t);
        if download_t == 0 and download_d == 0 and upload_t > 0 and upload_d == 0:
            self.uploadController.updateStatus(self.threadID, 'Ready for upload', file_size=upload_t)
            self.file_size = float(upload_t)
        elif download_t == 0 and download_d == 0 and upload_t > 0 and upload_d > 0:
            percent = upload_d / self.file_size
            kbspeed = ''
            if speed:
                kbspeed = str(speed / 1024) + 'Kb/s'
            self.uploadController.updateStatus(self.threadID, 'Uploading %.2f%%' % (percent * 100), speed=kbspeed)
        elif download_t > 0 and download_d == 0 and upload_t == self.file_size and upload_d == self.file_size:
            self.uploaded_file_id = download_t
            self.uploadController.updateStatus(self.threadID, 'Completed with file_id=%s' % (download_t))
        else:
            self.uploadController.updateStatus(self.threadID, 'Unknow state')
class UploadThread(QtCore.QThread):
    def __init__(self, uploadController, threadid, file_path, username, password, folder_id=None):
        super(UploadThread, self).__init__()

        #   ::type: TabDownloadController
        #   threadID = filepath
        #   phai truyen mainwindows.
        self.username = username
        self.password = password
        self.storagonSDK = StoragonSDK(serverURL)
        self.threadID = threadid
        self.file_path = file_path
        self.upload_folder_id = folder_id
        self.uploadController = uploadController
        self.pausenow = False

    def run(self):
        login = self.storagonSDK.login(self.username, self.password)
        if login:
            self.threadID = self.threadID.decode("utf-8")
            print("ThreadID XXX : %s " % self.threadID)
            self.file_path = self.file_path.decode("utf-8")
            self.storagonSDK.uploadFile(filePath=self.file_path, folder_id=self.upload_folder_id,
                                        progressFunction=self.progressFunction)
            time.sleep(0.1)

    def checkAndWait(self):
        while True:
            if self.pausenow:
                time.sleep(0.5)
            else:
                break

    def progressFunction(self, file_id, download_d, file_size, upload_d, speed=None, links=None):
        """

        :param file_id: uploaded file_id
        :param download_d: 0
        :param upload_t: file_size
        :param upload_d: uploaded size
        :return:
        """
        #   self.threadID, self.site_upload, self.username
        self.checkAndWait()

        if file_id == 0 and download_d == 0 and file_size > 0 and upload_d == 0:
            self.uploadController.updateStatus(self.threadID, status='Uploading', file_size=file_size)
            self.file_size = float(file_size)
        elif file_id == 0 and download_d == 0 and file_size > 0 and upload_d > 0:
            percent = upload_d / self.file_size
            kbspeed = ''
            if speed:
                kbspeed = str(speed / 1024) + 'Kb/s'
            self.uploadController.updateStatus(self.threadID, status='Uploading %.2f%%' % (percent * 100),
                                               speed=kbspeed)
        elif links and download_d == 0 and file_size == self.file_size and upload_d == self.file_size:
            self.uploadController.updateStatus(self.threadID, status='Completed', links=links)
        else:
            self.uploadController.updateStatus(self.threadID, status='Unknow state')

    def stop_uploadthread(self):
        self.storagonSDK.stop_thread()
class UploadThread(QtCore.QThread):
    def __init__(self, uploadQueue, uploadController, appFolderPath):
        super(UploadThread, self).__init__()
        # ::type: TabDownloadController
        # threadID = filepath

        # phai truyen mainwindows.
        self.appFolderPath = appFolderPath
        self.uploadController = uploadController
        self.uploadQueue = uploadQueue
        self.pausenow = False
        # self.stop = False
        self.statusqueueworker = Queue.Queue()
        self.statusqueueworker.put(True)

    def run(self):
        # self.checkAndWait()
        # print(u"Upload thread start to upload "+self.file_path)
        # self.uploadController.setStatusBar('Uploading...')

        while 1:
            # file, site_upload, username, password
            self.statusqueueworker.get()
            upload_info = self.uploadQueue.get()
            time.sleep(0.5)
            if len(upload_info) == 8:
                self.threadID, self.site_upload, self.username, self.password, self.browser, self.ftp_host, self.ftp_login, self.ftp_password = upload_info
                self.threadID = self.threadID.decode("utf-8")
                download_link = self.upload_file(self.threadID, self.site_upload, self.username, self.password,
                                                 self.ftp_host, self.ftp_login, self.ftp_password)

            else:

                self.total_fileupload, self.movies_info, self.remote_setting = upload_info
                list_downloadlink = []
                list_downloadlink_torrent = []
                for line_upload in self.total_fileupload:
                    # self.threadID = line_upload
                    list_upload = self.uploadController.mainWindow.get_list_site_upload(line_upload)
                    for line_f_upload in list_upload:
                        self.site_upload = line_f_upload.keys()[0]
                        info_upload = line_f_upload.values()[0]
                        self.threadID = info_upload['file']
                        self.username = info_upload['username']
                        self.password = info_upload['password']
                        self.ftp_host = info_upload['ftp_host']
                        self.ftp_login = info_upload['ftp_login']
                        self.ftp_password = info_upload['ftp_password']
                        self.uploadController.updateStatus(self.threadID, host=self.site_upload,
                                                           username=self.username, status='Ready for upload',
                                                           type_status='Upload')
                        download_link = self.upload_file(self.threadID, self.site_upload, self.username, self.password,
                                                         self.ftp_host, self.ftp_login, self.ftp_password)
                        print download_link
                        if self.site_upload == 'Storagon' and download_link:
                            list_downloadlink.append(download_link)
                            list_downloadlink_torrent.append(download_link + '?auto=torrent')
                    if self.remote_setting['leech_remove_file']:
                        i = 0
                        while i < 5:
                            try:
                                os.remove(u'' + line_upload)
                            except:
                                time.sleep(1)
                            else:
                                break
                            i += 1

                if list_downloadlink:
                    list_downloadlink.sort()
                    list_downloadlink_torrent.sort()
                    self.movies_info.link_download = {'Storagon': list_downloadlink,
                                                      'Storagon torrent': list_downloadlink_torrent}
                # movieinfo.name
                file_save = self.movies_info.name.decode('utf-8', 'ignore').\
                    replace('/', '-').replace("\\", '-').replace(':', '-').replace('*', '').replace('?', '')
                path_filesave = os.path.join(self.remote_setting['save_leechpath'].strip().decode('utf-8'),
                                             file_save + '.txt')

                try:
                    f = open(u'' + path_filesave, 'w')
                    f.write(self.movies_info.toBBcode() + '\n===\n')
                    f.write(self.movies_info.toHTML())
                    f.close()
                    lf = open(os.path.join(self.appFolderPath, 'leeched_database.txt'), 'a')
                    name_file = re.sub(r' +', ' ', re.sub(r'<.+?>|&.+?;', '',
                                                          re.sub(r'</p>|<br\s*/>', '\n', self.movies_info.name,
                                                                 re.DOTALL)))
                    lf.write(name_file + '\n')
                    lf.close()
                except Exception as e:
                    print e
                self.uploadController.updateStatus(file_save, status=path_filesave, type_status='Leech_completed')
                if self.movies_info.poster and self.remote_setting['leech_auto_post_blog'] and self.remote_setting[
                    'leech_blog_link'] and self.remote_setting['leech_blog_username'] and self.remote_setting[
                    'leech_blog_password']:
                    listcategory = []
                    listtag = []
                    if self.remote_setting['leech_blog_listcategory']:
                        listcategorys = self.remote_setting['leech_blog_listcategory']
                        if listcategorys.find(',') != -1:
                            for line_calog in listcategorys.split(','):
                                listcategory.append(line_calog.strip())
                        else:
                            listcategory.append(listcategorys.strip())
                    if self.remote_setting['leech_blog_listtag']:
                        listtags = self.remote_setting['leech_blog_listtag']
                        if listtags.find(',') != -1:
                            for line_tag in listtags.split(','):
                                listtag.append(line_tag.strip())
                        else:
                            listtag.append(listtags.strip())
                    print '===Post to your blog==='
                    poster = wppost.Wppost()
                    poster.post(self.remote_setting['leech_blog_link'].strip(),
                                self.remote_setting['leech_blog_username'].strip(),
                                self.remote_setting['leech_blog_password'].strip(), self.movies_info.name,
                                self.movies_info.toHTML(), listcategory, listtag)

            self.statusqueueworker.put(True)
            time.sleep(0.1)

    def upload_file(self, file, site_upload, username, password, ftp_host='', ftp_login='', ftp_password=''):
        # print file
        if site_upload == 'Storagon':
            self.uploadSKD = StoragonSDK()
        elif site_upload.find('rapidgator') != -1:
            self.uploadSKD = rapidgatorSDK.Rapidgator(browser=self.browser)
        else:
            self.uploadSKD = ftpSDK.FtpSDK(browser=self.browser)
        i = 0
        while i < 5:
            try:
                if site_upload == 'Storagon':
                    login = self.uploadSKD.login(username, password)
                else:
                    login = self.uploadSKD.login(email=username, password=password,
                                                 ftp_host=ftp_host, ftp_login=ftp_login,
                                                 ftp_password=ftp_password)
                if not login:
                    i += 1
                    continue
                if site_upload == 'Storagon':
                    link_down = self.uploadSKD.uploadFile(file, progressFunction=self.progressFunction)
                else:
                    link_down = self.uploadSKD.uploadFile(file, progressFunction=self.progressFunction,
                                                          username=username, password=password)
                if link_down:
                    return link_down
                    # return link_down
            except Exception as e:
                print e
                time.sleep(1)
            else:
                break
            i += 1
        if i >= 5:
            self.uploadController.updateStatus(file, status='Cant login to your account',
                                               host=site_upload, username=username)

    def checkAndWait(self):
        while True:
            if self.pausenow:
                time.sleep(0.5)
            else:
                break

    def progressFunction(self, file_id, download_d, file_size, upload_d, speed=None, link=None):
        """
        :param file_id: uploaded file_id
        :param download_d: 0
        :param upload_t: file_size
        :param upload_d: uploaded size
        :return:
        """
        # self.threadID, self.site_upload, self.username
        self.checkAndWait()

        if file_id == 0 and download_d == 0 and file_size > 0 and upload_d == 0:
            self.uploadController.updateStatus(self.threadID, status='Uploading', file_size=file_size,
                                               host=self.site_upload, username=self.username, type_status="Upload")
            self.file_size = float(file_size)
        elif file_id == 0 and download_d == 0 and file_size > 0 and upload_d > 0:
            percent = upload_d / self.file_size
            kbspeed = ''
            if speed:
                kbspeed = str(speed / 1024) + 'Kb/s'
            self.uploadController.updateStatus(self.threadID, status='Uploading %.2f%%' % (percent * 100),
                                               speed=kbspeed, host=self.site_upload, username=self.username,
                                               type_status="Upload")
        elif link and download_d == 0 and file_size == self.file_size and upload_d == self.file_size:
            self.uploadController.updateStatus(self.threadID, status='Completed', host=self.site_upload,
                                               username=self.username, link=link, type_status="Upload")
        else:
            self.uploadController.updateStatus(self.threadID, status='Unknow state', host=self.site_upload,
                                               username=self.username, type_status="Upload")

    def stop_uploadthread(self):
        if self.site_upload == 'Storagon':
            self.uploadSKD.stop_thread()