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

__author__ = 'helljump'

import logging
import startup
from utils import MyProgressDialog
from PyQt4 import QtGui
import re
from pytils.translit import slugify
import codecs
from textdir_f import ImageWriter


log = logging.getLogger(__name__)

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


TAG = '''\
INSERT INTO `dle_tags` (`news_id`, `tag`) VALUES (@postid,'%(tag)s');
'''

CAT = '''\
INSERT INTO `dle_category` (`name`, `alt_name`, `keywords`) VALUES ('%(title)s', '%(slug)s', '');
SET @catid = last_insert_id();

'''

POST = '''\
INSERT INTO `dle_post`
    (`autor`, `date`, `short_story`, `full_story`, `xfields`, `title`, `descr`, `keywords`, `category`,
        `alt_name`, `tags`, `approve`)
VALUES ('admin','%(date)s','%(intro)s','%(full)s','','%(title)s','','', @catid,'%(slug)s','%(tags)s', 1);
SET @postid = last_insert_id();
INSERT INTO `dle_post_extras` (`news_id`, `user_id`) VALUES (@postid,1);

'''


def sql_quote(text):
    text = unicode(text)
    text = text.replace("&mdash;", "-")
    return text.replace(r"'", r"\'").replace("\"", r"\"").replace("\n", "\\n")


def _write(prj, path):
    docs = prj.root()['documents']
    docs = sorted(docs, key=lambda doc: str(doc.cats))
    iwriter = ImageWriter(prj, path, 'uploads/posts', '/uploads/posts')
    lastcat = None
    fout = codecs.open(path, 'w', 'utf-8', 'replace')
    for j, doc in enumerate(docs):
        cat = list(doc.cats)[0] if len(doc.cats) > 0 else u'Новости'
        if lastcat != cat:
            #add cat
            fout.write(CAT % {'title': cat, 'slug': slugify(cat)})
            lastcat = cat
        text = iwriter(doc)
        try:
            intro, full = splitter.split(text)
        except ValueError:
            intro = text
            full = ''
        params = {
            'date': doc.date,
            'intro': sql_quote(intro),
            'full': sql_quote(full),
            'title': doc.title,
            'slug': slugify(doc.title),
            'tags': ', '.join(doc.tags)
        }
        fout.write(POST % params)
        for tag in doc.tags:
            fout.write(TAG % {'tag': tag})
        yield j
    fout.close()


def writer(parent):
    prj = parent.project
    fn = QtGui.QFileDialog.getSaveFileName(parent, u'Экспорт', filter=u'DataLife Engine SQL (*.sql)')
    if fn.isEmpty():
        return False
    fn = unicode(fn)
    l = len(prj.root()['documents'])
    pdlg = MyProgressDialog(u'Экспорт', u'Запись файлов', u'Отмена', 0, l, parent=parent)
    pdlg.show()
    try:
        for j in _write(prj, fn):
            pdlg.setValue(j)
            if pdlg.wasCanceled():
                raise IOError('Canceled')
        log.debug('done')
        pdlg.close()
    finally:
        pdlg.close()
    QtGui.QMessageBox.information(parent, u'Экспорт', u'Экспорт выполнен.\n'
        u'Перед загрузкой SQL очистите кэш категорий, удалив файл'
        u'\n"/engine/cache/system/category.php" в каталоге DLE.')


if __name__ == '__main__':
    '''read'''
    #path = ur'd:\work\cm2\test\кат'
    #for doc in _read(path):
    #    print doc.title, doc.cats

    '''write'''
    root = startup.CONN.root()
    prj = root["projects"][0]
    prj.open()
    #dlg = Dialog(prj)
    #dlg.exec_()
    for j in _write(prj, ur'd:\work2014\cm3\_test\dle\docs.sql'):
        print j,
    prj.close()
