#!/usr/bin/env python
#-*- coding: UTF-8 -*-

__author__ = 'helljump'

import logging
from PyQt4 import QtCore
from PyQt4 import QtGui
from datetime import datetime
import random
from lxml.html.clean import Cleaner
from time import time


log = logging.getLogger(__name__)


class MyProgressDialog(QtGui.QProgressDialog):

    closed = QtCore.pyqtSignal()

    def __init__(self, title, label, cancel, from_=0, to=0, parent=None):
        super(MyProgressDialog, self).__init__(label, cancel, from_, to, parent)
        self.setWindowTitle(title)
        self.setModal(True)
        self.setFixedWidth(320)
        self.timer = time()

    def set_value(self, v):
        if self.timer + 0.2 < time():
            self.setValue(v)
            self.timer = time()
            QtGui.qApp.processEvents()

    def set_text(self, text):
        if isinstance(text, str):
            text = unicode(text, 'utf-8', 'replace')
        if self.timer + 0.2 < time():
            self.setLabelText(text)
            self.timer = time()
            QtGui.qApp.processEvents()

    def inc_value(self, v=1):
        self.setValue(self.value() + v)

    def set_range(self, from_, to):
        self.setRange(from_, to)
        self.setValue(from_)

    def inc_range(self, by=1):
        self.setMaximum(self.pdlg.maximum() + by)

    def hideEvent(self, evt):
        log.debug('emit close')
        self.closed.emit()
        evt.accept()


def random_date():
    oneyear = datetime.timedelta(days=365)
    to_date = datetime.datetime.now()
    from_date = to_date - oneyear
    a = time.mktime(from_date.timetuple())
    b = time.mktime(to_date.timetuple())
    date = datetime.fromtimestamp(random.randint(a, b))


def clean_html():
    cleaner = Cleaner(style=False, page_structure=False, safe_attrs_only=False)
    #html = self.page.mainFrame().toHtml()
    #html = re.sub('</?(html|body|head)[^>]*>', '', unicode(html))
    #html = cleaner.clean_html(unicode(html))
    #tree = xhtml.fromstring(html)
    #html = xhtml.tostring(tree, pretty_print=True, encoding=unicode)
    #html = html[6:-8]  # .strip('<div>').strip('</div>')
