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

__author__ = 'helljump'

from PyQt4 import QtGui
from PyQt4 import QtCore
import logging
import startup
from ui.profiles_ui import Ui_Dialog
import transaction
import wprpc_p
import twitter_p
import yaru_p
import ljcom_p
import bloggercom_p
from functools import partial
import sys


log = logging.getLogger(__name__)


class ProfilesModel(QtCore.QAbstractTableModel):

    def __init__(self, profiles, parent):
        super(ProfilesModel, self).__init__(parent)
        self.labels = [u'Наименование', u'Тип']
        self._data = profiles

    def rowCount(self, parent=QtCore.QModelIndex()):
        return len(self._data)

    def columnCount(self, parent=QtCore.QModelIndex()):
        return len(self.labels)

    def headerData(self, section, orientation, role):
        egg = QtCore.QVariant()
        if orientation == QtCore.Qt.Horizontal and role == QtCore.Qt.DisplayRole:
            egg = QtCore.QVariant(self.labels[section])
        elif orientation == QtCore.Qt.Vertical and role == QtCore.Qt.DisplayRole:
            egg = QtCore.QVariant(section + 1)
        return egg

    def flags(self, index):
        egg = QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled
        return egg

    def data(self, index, role=QtCore.Qt.DisplayRole):
        if not index.isValid():
            return None
        item = self._data[index.row()]
        if role == QtCore.Qt.DisplayRole or role == QtCore.Qt.EditRole:
            if index.column() == 0:
                return item.title
            else:
                module = sys.modules[item.__module__]
                return module.DESC
        elif role == QtCore.Qt.UserRole + 1:
            return item
        return QtCore.QVariant()

    def remove_rows(self, indexes, parent=QtCore.QModelIndex()):
        rows = [ndx.row() for ndx in indexes if ndx.column() == 0]
        rows.sort(reverse=True)
        for row in rows:
            self.beginRemoveRows(parent, row, row)
            del self._data[row]
            self.endRemoveRows()

    def add_item(self, item):
        r = len(self._data)
        self.beginInsertRows(QtCore.QModelIndex(), r, r)
        self._data.append(item)
        self.endInsertRows()
        return self.createIndex(r, 1)


class ProfileDialog(QtGui.QDialog):

    def __init__(self, parent):
        super(ProfileDialog, self).__init__(parent)
        self.setWindowTitle(u'Профиль')
        self.setMinimumWidth(500)
        self.setModal(True)
        self.gridLayout_2 = QtGui.QGridLayout(self)
        self.buttonBox = QtGui.QDialogButtonBox(self)
        self.buttonBox.setOrientation(QtCore.Qt.Horizontal)
        self.buttonBox.setStandardButtons(QtGui.QDialogButtonBox.Cancel | QtGui.QDialogButtonBox.Ok)
        self.gridLayout_2.addWidget(self.buttonBox, 1, 0)
        self.buttonBox.accepted.connect(self.accept)
        self.buttonBox.rejected.connect(self.reject)

    def closeEvent(self, event):
        log.debug('closed')
        #rc = QtGui.QMessageBox.question(self, u'Профиль', u'Сохранить изменения?',
        #    QtGui.QMessageBox.Yes | QtGui.QMessageBox.No)
        #if rc == QtGui.QMessageBox.Yes:
        #    self.setResult(1)
        event.accept()


class Dialog(QtGui.QDialog, Ui_Dialog):
    def __init__(self, project, parent=None):
        super(Dialog, self).__init__(parent)
        self.setupUi(self)
        self.prj = project
        self.parent = parent
        self.profile = project.root()['profile']
        if startup.CFG.contains('profiles/geometry'):
            self.restoreGeometry(startup.CFG.value('profiles/geometry').toByteArray())
        menu1 = QtGui.QMenu(self)
        menu1.addAction(wprpc_p.DESC, partial(self.new_profile, wprpc_p))
        menu1.addAction(twitter_p.DESC, partial(self.new_profile, twitter_p))
        menu1.addAction(yaru_p.DESC, partial(self.new_profile, yaru_p))
        menu1.addAction(ljcom_p.DESC, partial(self.new_profile, ljcom_p))
        menu1.addAction(bloggercom_p.DESC, partial(self.new_profile, bloggercom_p))
        self.actionNew.setMenu(menu1)
        self.model = ProfilesModel(self.profile, self)
        self.tv.setModel(self.model)

    def closeEvent(self, evt):
        log.debug('close event')
        startup.CFG.setValue('profiles/geometry', self.saveGeometry())
        evt.accept()

    @QtCore.pyqtSlot()
    def on_actionRemove_triggered(self):
        log.debug('delete')
        rc = QtGui.QMessageBox.question(self, u'Редактор профилей', u'Удалить профиль?',
            QtGui.QMessageBox.Yes | QtGui.QMessageBox.No)
        if rc == QtGui.QMessageBox.No:
            return
        self.model.remove_rows(self.tv.selectedIndexes())
        transaction.commit()

    @QtCore.pyqtSlot(QtCore.QModelIndex)
    def on_tv_doubleClicked(self, index):
        log.debug('edit profile')
        profile = self.tv.model().data(index, QtCore.Qt.UserRole + 1)
        module = sys.modules[profile.__module__]
        d = ProfileDialog(self)
        e = module.Editor(profile, d)
        e.gridLayout.setMargin(0)
        if d.exec_():
            e.get_profile()
            transaction.commit()

    def new_profile(self, module):
        log.debug('new %s', module.DESC)
        d = ProfileDialog(self)
        e = module.Editor(None, d)
        e.gridLayout.setMargin(0)
        if d.exec_():
            profile = e.get_profile()
            self.model.add_item(profile)
            transaction.commit()


if __name__ == '__main__':
    logging.basicConfig(level=logging.DEBUG)
    root = startup.CONN.root()
    prj = root["projects"][0]
    prj.open()
    dlg = Dialog(prj)
    rc = dlg.exec_()
    prj.close()
