#!/usr/bin/env python2
# vim:fileencoding=utf-8
from __future__ import (unicode_literals, division, absolute_import,
                        print_function)

__license__ = 'GPL v3'
__copyright__ = '2013, Kovid Goyal <kovid at kovidgoyal.net>'

from PyQt4.Qt import (
    QDialog, pyqtSignal, QIcon, QVBoxLayout, QDialogButtonBox, QStackedWidget,
    QAction, QMenu, QTreeWidget, QTreeWidgetItem, QGridLayout, QWidget, Qt,
    QSize, QStyledItemDelegate, QApplication, QTimer)

from calibre.constants import plugins
from calibre.ebooks.oeb.polish.toc import commit_toc, get_toc
from calibre.gui2 import gprefs, error_dialog
from calibre.gui2.toc.main import TOCView, ItemEdit
from calibre.gui2.tweak_book import current_container, TOP, actions

class TOCEditor(QDialog):

    explode_done = pyqtSignal(object)
    writing_done = pyqtSignal(object)

    def __init__(self, title=None, parent=None):
        QDialog.__init__(self, parent)

        t = title or current_container().mi.title
        self.book_title = t
        self.setWindowTitle(_('Edit the ToC in %s')%t)
        self.setWindowIcon(QIcon(I('toc.png')))

        l = self.l = QVBoxLayout()
        self.setLayout(l)

        self.stacks = s = QStackedWidget(self)
        l.addWidget(s)
        self.toc_view = TOCView(self)
        self.toc_view.add_new_item.connect(self.add_new_item)
        s.addWidget(self.toc_view)
        self.item_edit = ItemEdit(self)
        s.addWidget(self.item_edit)

        bb = self.bb = QDialogButtonBox(QDialogButtonBox.Ok|QDialogButtonBox.Cancel)
        l.addWidget(bb)
        bb.accepted.connect(self.accept)
        bb.rejected.connect(self.reject)

        self.read_toc()

        self.resize(950, 630)
        geom = gprefs.get('toc_editor_window_geom', None)
        if geom is not None:
            self.restoreGeometry(bytes(geom))

    def add_new_item(self, item, where):
        self.item_edit(item, where)
        self.stacks.setCurrentIndex(1)

    def accept(self):
        if self.stacks.currentIndex() == 1:
            self.toc_view.update_item(*self.item_edit.result)
            gprefs['toc_edit_splitter_state'] = bytearray(self.item_edit.splitter.saveState())
            self.stacks.setCurrentIndex(0)
        elif self.stacks.currentIndex() == 0:
            self.write_toc()
            super(TOCEditor, self).accept()

    def really_accept(self, tb):
        gprefs['toc_editor_window_geom'] = bytearray(self.saveGeometry())
        if tb:
            error_dialog(self, _('Failed to write book'),
                _('Could not write %s. Click "Show details" for'
                  ' more information.')%self.book_title, det_msg=tb, show=True)
            gprefs['toc_editor_window_geom'] = bytearray(self.saveGeometry())
            super(TOCEditor, self).reject()
            return

        super(TOCEditor, self).accept()

    def reject(self):
        if not self.bb.isEnabled():
            return
        if self.stacks.currentIndex() == 1:
            gprefs['toc_edit_splitter_state'] = bytearray(self.item_edit.splitter.saveState())
            self.stacks.setCurrentIndex(0)
        else:
            gprefs['toc_editor_window_geom'] = bytearray(self.saveGeometry())
            super(TOCEditor, self).reject()

    def read_toc(self):
        self.toc_view(current_container())
        self.item_edit.load(current_container())
        self.stacks.setCurrentIndex(0)

    def write_toc(self):
        toc = self.toc_view.create_toc()
        commit_toc(current_container(), toc, lang=self.toc_view.toc_lang,
                uid=self.toc_view.toc_uid)

DEST_ROLE = Qt.UserRole
FRAG_ROLE = DEST_ROLE + 1

class Delegate(QStyledItemDelegate):

    def sizeHint(self, *args):
        ans = QStyledItemDelegate.sizeHint(self, *args)
        return ans + QSize(0, 10)

class TOCViewer(QWidget):

    navigate_requested = pyqtSignal(object, object)

    def __init__(self, parent=None):
        QWidget.__init__(self, parent)
        self.l = l = QGridLayout(self)
        self.setLayout(l)
        l.setContentsMargins(0, 0, 0, 0)

        self.is_visible = False
        self.view = QTreeWidget(self)
        self.delegate = Delegate(self.view)
        self.view.setItemDelegate(self.delegate)
        self.view.setHeaderHidden(True)
        self.view.setAnimated(True)
        self.view.setContextMenuPolicy(Qt.CustomContextMenu)
        self.view.customContextMenuRequested.connect(self.show_context_menu, type=Qt.QueuedConnection)
        self.view.itemActivated.connect(self.emit_navigate)
        self.view.itemPressed.connect(self.item_pressed)
        pi = plugins['progress_indicator'][0]
        if hasattr(pi, 'set_no_activate_on_click'):
            pi.set_no_activate_on_click(self.view)
        self.view.itemDoubleClicked.connect(self.emit_navigate)
        l.addWidget(self.view)

        self.refresh_action = QAction(QIcon(I('view-refresh.png')), _('&Refresh'), self)
        self.refresh_action.triggered.connect(self.build)

    def item_pressed(self, item):
        if QApplication.mouseButtons() & Qt.LeftButton:
            QTimer.singleShot(0, self.emit_navigate)

    def show_context_menu(self, pos):
        menu = QMenu(self)
        menu.addAction(actions['edit-toc'])
        menu.addAction(_('&Expand all'), self.view.expandAll)
        menu.addAction(_('&Collapse all'), self.view.collapseAll)
        menu.addAction(self.refresh_action)
        menu.exec_(self.view.mapToGlobal(pos))

    def iteritems(self, parent=None):
        if parent is None:
            parent = self.invisibleRootItem()
        for i in xrange(parent.childCount()):
            child = parent.child(i)
            yield child
            for gc in self.iteritems(parent=child):
                yield gc

    def emit_navigate(self, *args):
        item = self.view.currentItem()
        if item is not None:
            dest = unicode(item.data(0, DEST_ROLE).toString())
            frag = unicode(item.data(0, FRAG_ROLE).toString())
            if not frag:
                frag = TOP
            self.navigate_requested.emit(dest, frag)

    def build(self):
        c = current_container()
        if c is None:
            return
        toc = get_toc(c, verify_destinations=False)

        def process_node(toc, parent):
            for child in toc:
                node = QTreeWidgetItem(parent)
                node.setText(0, child.title or '')
                node.setData(0, DEST_ROLE, child.dest or '')
                node.setData(0, FRAG_ROLE, child.frag or '')
                tt = _('File: {0}\nAnchor: {1}').format(
                    child.dest or '', child.frag or _('Top of file'))
                node.setData(0, Qt.ToolTipRole, tt)
                process_node(child, node)

        self.view.clear()
        process_node(toc, self.view.invisibleRootItem())

    def visibility_changed(self, visible):
        self.is_visible = visible
        if visible:
            self.build()

    def update_if_visible(self):
        if self.is_visible:
            self.build()

