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

DESC = u"Livejournal.com"

__author__ = 'helljump'

import sys
from PyQt4 import QtCore
from PyQt4 import QtGui
import logging
from ui.ljcom_ui import Ui_Frame
from utils import MyProgressDialog
from persistent import Persistent
import startup
from dbobj import Document
import transaction
import re
import hashlib
import xmlrpclib
import requests
import random
import os
from utils import savepics_su


log = logging.getLogger(__name__)

DEBUG = __name__ == '__main__'
INTERFACE = "http://www.livejournal.com/interface/xmlrpc"


class RequestsTransport(xmlrpclib.Transport):
    user_agent = "CM2Publisher/2"
    use_https = False

    def __init__(self):
        xmlrpclib.Transport.__init__(self)
        self.cookies = {}
        self.proxies = None

    def request(self, host, handler, request_body, verbose):
        headers = {'User-Agent': self.user_agent}
        if self.cookies:
            headers.update({"X-LJ-Auth": "cookie"})
        url = self._build_url(host, handler)
        try:
            resp = requests.post(url, data=request_body, headers=headers,
                                 cookies=self.cookies, proxies=self.proxies)
        except ValueError:
            raise
        except Exception:
            raise  # something went wrong
        else:
            try:
                resp.raise_for_status()
            except requests.RequestException as e:
                raise xmlrpclib.ProtocolError(url, resp.status_code, str(e),
                                              resp.headers)
            else:
                return self.parse_response(resp)

    def parse_response(self, resp):
        p, u = self.getparser()
        p.feed(resp.text)
        p.close()
        return u.close()

    def _build_url(self, host, handler):
        scheme = 'https' if self.use_https else 'http'
        return '%s://%s/%s' % (scheme, host, handler)

    def set_cookie(self, cookie):
        self.cookies = {"ljsession": cookie}

    def set_proxy(self, proxy):
        self.proxies = {"http": proxy, "https": proxy}


class Poster(object):
    MORE_RE = re.compile("<hr class=['\"]?more['\"]?>")

    def __init__(self, project, profile):
        self.project = project
        self.profile = profile
        root = project.root()
        prefs = root['prefs']
        proxy_file = prefs.get('proxy_file', '')
        #pampam
        transport = RequestsTransport()
        if proxy_file and os.path.isfile(proxy_file):
            plist = [addr.strip() for addr in open(proxy_file, "r") if len(addr.strip()) > 3]
            transport.set_proxy(random.choice(plist))
            self.imup = savepics_su.Uploader(proxy=proxy_file, connection=project.con())
        else:
            self.imup = savepics_su.Uploader(proxy=None, connection=project.con())
        self.srv = xmlrpclib.ServerProxy(INTERFACE, transport=transport)
        params = {"username": profile.username, "hpassword": profile.hash, "expiration": "short"}
        rc = self.srv.LJ.XMLRPC.sessiongenerate(params)
        cookie = rc["ljsession"]
        transport.set_cookie(cookie)

    def __call__(self, doc):
        self.imup.upload_doc(doc)
        text = re.sub(self.MORE_RE, '', doc.text)
        #pumpum
        params = {
            "username": self.profile.username,
            'auth_method': "cookie",
            "event": text,
            "subject": doc.title,
            "year": doc.date.year,
            "mon": doc.date.month,
            "day": doc.date.day,
            "hour": doc.date.hour,
            "min": doc.date.minute,
            "props": {
                "taglist": ", ".join(doc.tags),
                "opt_backdated": True
            }
        }
        rc = self.srv.LJ.XMLRPC.postevent(params)
        doc.pid = int(rc["itemid"])
        doc.state = Document.PUBLIC
        log.debug('published %s', doc.pid)


def post_all(prj):
    conn = prj.new_con()
    try:
        root = conn.root()
        docs = root['documents']
        profile = root['profile']
        prefs = root['prefs']
        timeout = prefs.get('timeout', 10)
        proxy_file = prefs.get('proxy_file', '')

        transport = RequestsTransport()
        if proxy_file and os.path.isfile(proxy_file):
            plist = [addr.strip() for addr in open(proxy_file, "r") if len(addr.strip()) > 3]
            transport.set_proxy(random.choice(plist))
            imup = savepics_su.Uploader(proxy=proxy_file, connection=conn)
        else:
            imup = savepics_su.Uploader(proxy=None, connection=conn)
        srv = xmlrpclib.ServerProxy(INTERFACE, transport=transport)
        params = {"username": profile.username, "hpassword": profile.hash, "expiration": "short"}
        rc = srv.LJ.XMLRPC.sessiongenerate(params)
        cookie = rc["ljsession"]
        transport.set_cookie(cookie)

        for j, doc in enumerate(docs, 1):
            if doc.state != Document.READY:
                yield j
                continue
            #text = re.sub('<img src=[\'"]cm3\://image/\d+[\'"][^>]*>', '', doc.text)
            imup.upload_doc(doc)
            text = re.sub("<hr class=['\"]?more['\"]?>", '', doc.text)
            params = {
                "username": profile.username,
                'auth_method': "cookie",
                "event": text,
                "subject": doc.title,
                "year": doc.date.year,
                "mon": doc.date.month,
                "day": doc.date.day,
                "hour": doc.date.hour,
                "min": doc.date.minute,
                "props": {
                    "taglist": ", ".join(doc.tags),
                    "opt_backdated": True
                }
            }
            if doc.pid is None:
                rc = srv.LJ.XMLRPC.postevent(params)
                doc.pid = int(rc["itemid"])
            else:
                params["itemid"] = doc.pid
                rc = srv.LJ.XMLRPC.editevent(params)
            if not DEBUG:
                doc.state = Document.PUBLIC
            transaction.commit()
            log.debug('published %s', doc.pid)
            yield j
            QtCore.QThread.sleep(timeout)
    except:
        transaction.abort()
        raise
    finally:
        conn.close()


class LJProfile(Persistent):
    def __init__(self):
        self.title = ""
        self.username = ""
        self.hash = ""


class TestThread(QtCore.QThread):
    done = QtCore.pyqtSignal(unicode)

    def __init__(self, parent, **kwargs):
        QtCore.QThread.__init__(self, parent)
        self.kwargs = kwargs

    def run(self):
        try:
            transport = RequestsTransport()
            conn = xmlrpclib.ServerProxy(INTERFACE, transport=transport)
            params = {"username": self.kwargs['username'], "hpassword": self.kwargs['hash_']}
            #print params
            conn.LJ.XMLRPC.login(params)
            self.done.emit(u'Удачно подключено')
        except:
            exctype, value = sys.exc_info()[:2]
            self.done.emit(u'Что-то пошло не так: %s' % unicode(value))


class Editor(QtGui.QFrame, Ui_Frame):
    def __init__(self, profile=None, parent=None):
        QtGui.QFrame.__init__(self, parent)
        self.setupUi(self)
        self.profile = profile if profile else LJProfile()
        self.title_le.setText(self.profile.title)
        self.username_le.setText(self.profile.username)
        self.hash_le.setText(self.profile.hash)
        self.hash_le.setEchoMode(QtGui.QLineEdit.Password)
        parent.gridLayout_2.addWidget(self, 0, 0)

    @QtCore.pyqtSlot()
    def on_hash_le_clicked(self):
        passwd, ok = QtGui.QInputDialog.getText(self, DESC, u'Введите пароль')
        if not ok:
            return
        egg = hashlib.md5()
        egg.update(unicode(passwd))
        self.hash_le.setText(egg.hexdigest())

    @QtCore.pyqtSlot()
    def on_test_pb_clicked(self):
        prog = MyProgressDialog(u'Тестовое подключение', u'Подключаемся', u'Отмена', parent=self)
        th = TestThread(self, username=unicode(self.username_le.text()), hash=unicode(self.hash_le.text))

        def closed():
            log.debug('hashed')
            th.done.disconnect()

        def done(msg):
            prog.close()
            QtGui.QMessageBox.information(self, u'Подключение', msg)

        th.done.connect(done)
        prog.closed.connect(closed)

        th.start()
        prog.show()

    def get_profile(self):
        self.profile.title = unicode(self.title_le.text())
        self.profile.username = unicode(self.username_le.text())
        self.profile.hash = unicode(self.hash_le.text)
        return self.profile


if __name__ == "__main__":
    root = startup.CONN.root()
    prj = root["projects"][3]
    prj.open()
    for j in post_all(prj):
        print j,
    prj.close()
