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

DESC = u"Я.ру API"

__author__ = 'helljump'


import sys
from PyQt4 import QtCore
from PyQt4 import QtGui
import logging
from ui.yaru_ui import Ui_Frame
from utils import MyProgressDialog
from persistent import Persistent
import startup
from dbobj import Document
import transaction
import re
import grab
import json
from lxml.builder import ElementMaker
from lxml import etree
from utils import savepics_su


log = logging.getLogger(__name__)


DEBUG = __name__ == '__main__'
CLIENT_ID = ""
CLIENT_SECRET = ""

NAMESPACES = {
    "a": "http://www.w3.org/2005/Atom",
    "y": "http://api.yandex.ru/yaru/",
    "thr": "http://purl.org/syndication/thread/1.0"
    }

POSTNAMESPACES = {
    None: "http://www.w3.org/2005/Atom",
    "y": "http://api.yandex.ru/yaru/"
    }

R = ElementMaker(namespace="http://www.w3.org/2005/Atom", nsmap=POSTNAMESPACES)
Y = ElementMaker(namespace="http://api.yandex.ru/yaru/", nsmap=POSTNAMESPACES)
E = ElementMaker()


class Poster(object):

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

    def __init__(self, project, profile):
        self.project = project
        self.profile = profile
        self.g = grab.Grab()
        root = project.root()
        prefs = root['prefs']
        proxy = prefs.get('proxy_file', '')
        self.g.setup(headers={"Authorization": "OAuth %s" % profile.token})
        if proxy:
            self.g.load_proxylist(proxy, 'text_file', auto_init=True, auto_change=True)
            self.imup = savepics_su.Uploader(proxy=proxy, connection=project.con())
        else:
            self.imup = savepics_su.Uploader(proxy=None, connection=project.con())

    def __call__(self, doc):
        self.imup.upload_doc(doc)
        text = re.sub(self.MORE_RE, '', doc.text)
        content = E.content(type="html")
        content.text = etree.CDATA(text)
        egg = R.entry(
            E.category(scheme="urn:ya.ru:posttypes", term="text"),
            E.title(doc.title),
            content,
            Y.access(u"public"))
        tag_scheme = "https://api-yaru.yandex.ru/person/%s/tag" % self.profile.username
        for tag in doc.tags:
            t = E.category(term=tag, scheme=tag_scheme)
            egg.append(t)
        body = etree.tostring(egg, encoding=unicode)
        self.g.setup(post=body)
        self.g.go("https://api-yaru.yandex.ru/person/%s/post/" % self.profile.username)
        cid = self.g.doc.select('//entry/id').text()
        doc.pid = unicode(cid)
        doc.state = Document.PUBLIC
        log.debug('published %s', doc.pid)


def post_all(prj):
    conn = prj.new_con()
    g = grab.Grab()
    if DEBUG:
        g.setup(log_dir='_test/dump')
    try:
        root = conn.root()
        docs = root['documents']
        profile = root['profile']
        prefs = root['prefs']
        timeout = prefs.get('timeout', 10)
        proxy = prefs.get('proxy_file', '')
        g.setup(headers={"Authorization": "OAuth %s" % profile.token})
        if proxy:
            g.load_proxylist(proxy, 'text_file', auto_init=True, auto_change=True)
            imup = savepics_su.Uploader(proxy=proxy, connection=conn)
        else:
            imup = savepics_su.Uploader(proxy=None, connection=conn)
        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)
            content = E.content(type="html")
            content.text = etree.CDATA(text)
            egg = R.entry(
                E.category(scheme="urn:ya.ru:posttypes", term="text"),
                E.title(doc.title),
                content,
                Y.access(u"public"))
            tag_scheme = "https://api-yaru.yandex.ru/person/%s/tag" % profile.username
            for tag in doc.tags:
                t = E.category(term=tag, scheme=tag_scheme)
                egg.append(t)
            body = etree.tostring(egg, encoding=unicode)
            g.setup(post=body)
            g.go("https://api-yaru.yandex.ru/person/%s/post/" % profile.username)
            cid = g.doc.select('//entry/id').text()
            doc.pid = unicode(cid)
            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 YaRuProfile(Persistent):

    def __init__(self):
        self.title = ""
        self.username = ""
        self.token = ""


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:
            g = grab.Grab()
            rc = g.go("https://api-yaru.yandex.ru/me/?oauth_token=%s&format=json" % self.kwargs["token"])
            js = json.loads(rc.unicode_body())
            self.done.emit(u'Удачно подключено к %s' % js["id"])
        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 YaRuProfile()
        self.title_le.setText(self.profile.title)
        self.username_le.setText(self.profile.username)
        self.token_le.setText(self.profile.token)
        parent.gridLayout_2.addWidget(self, 0, 0)

    @QtCore.pyqtSlot()
    def on_auth_pb_clicked(self):
        try:
            auth_url = "https://oauth.yandex.ru/authorize?response_type=code&client_id=%s" % CLIENT_ID
            QtGui.QDesktopServices.openUrl(QtCore.QUrl(auth_url))
            verifier = QtGui.QInputDialog.getText(self, u'Авторизация', u'Введите код из окна браузера')[0]
            if verifier.isEmpty():
                return
            g = grab.Grab()
            g.setup(post={
                "grant_type": "authorization_code",
                "code": unicode(verifier),
                "client_id": CLIENT_ID,
                "client_secret": CLIENT_SECRET})
            rc = g.go("https://oauth.yandex.ru/token")
            js = json.loads(rc.unicode_body())
            access_token = js["access_token"]
            rc = g.go("https://api-yaru.yandex.ru/me/?oauth_token=%s&format=json" % access_token)
            js = json.loads(rc.unicode_body())
            user_id = js["id"].split("/")[1] 
            self.token_le.setText(access_token)
            self.username_le.setText(user_id)
        except:
            exctype, value = sys.exc_info()[:2]
            QtGui.QMessageBox.critical(self, u'Ошибка авторизации', unicode(value))

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

        def closed():
            log.debug('closed')
            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.token = unicode(self.token_le.text())
        return self.profile


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