#-*- coding:utf-8 -*-

#  Copyright © 2009, 2011-2015  B. Clausius <barcc@gmx.de>
#
#  This program is free software: you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation, either version 3 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program.  If not, see <http://www.gnu.org/licenses/>.


# pylint: disable=C0321

import os
import re
import html
from itertools import zip_longest

from PyQt5.QtCore import QAbstractAnimation, QEvent, QObject, QPropertyAnimation, QSize, QStandardPaths, Qt, QTimer
from PyQt5.QtCore import pyqtSignal as Signal, pyqtSlot as Slot
from PyQt5.QtGui import (QColor, QDesktopServices, QFontMetrics, QIcon, QIconEngine, QKeySequence, QPixmap,
                         QStandardItem, QStandardItemModel, QTextDocumentFragment)
from PyQt5.QtWidgets import (QAbstractItemDelegate, QColorDialog, QDialog, QDialogButtonBox, QFileDialog, QLabel,
                         QProgressDialog, QPushButton, QStyledItemDelegate, QTextEdit)

from . import config
from .settings import settings
from .theme import Theme
from .model import Model

try:
    _
except NameError:
    _ = lambda t: t
    

class Dialog (QDialog):
    _instance = None
    _classes = []
    
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        
        self.accepted.connect(self.on_response)
        self._ignore_changed = False
        self.bound = {}
        settings.keystore.changed.connect(self.on_settings_changed, Qt.QueuedConnection)
        
    @classmethod
    def run(cls, **kwargs):
        if cls._instance is None:
            cls._instance = cls(**kwargs)
            ret = cls._instance
            cls._classes.append(cls)
        else:
            ret = None
            cls._instance.move(cls._instance.pos())
        cls._instance.show()
        return ret
        
    @classmethod
    def delete(cls):
        while cls._classes:
            cls_ = cls._classes.pop(0)
            # pylint: disable=W0212
            cls_._instance.close()
            cls_._instance.deleteLater()
            # pylint: enable=W0212
            cls_._instance = None
            
    def bind(self, key, widget, getter, setter, signal):
        if isinstance(getter, str): getter = getattr(widget, getter)
        if isinstance(setter, str): setter = getattr(widget, setter)
        if isinstance(signal, str): signal = getattr(widget, signal)
        setter(getattr(settings, key))
        if signal is not None:
            signal.connect(lambda: self.on_widget_changed(key))
        self.bound[key] = (getter, setter, signal)
        
    @staticmethod
    def bind_reset(settings_key, button):
        button.clicked.connect(lambda: delattr(settings, settings_key))
        
    def on_response(self):
        pass
        
    def on_widget_changed(self, key):
        if self._ignore_changed:
            return
        try:
            getter = self.bound[key][0]
        except KeyError:
            return
        self._ignore_changed = True
        setattr(settings, key, getter())
        self._ignore_changed = False
        
    def on_settings_changed(self, key):
        if self._ignore_changed:
            return
        try:
            setter = self.bound[key][1]
        except KeyError:
            return
        self._ignore_changed = True
        setter(getattr(settings, key))
        self._ignore_changed = False
        
        
class ColorIconEngine (QIconEngine):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        
        self.color = 'black'
        
    def paint(self, painter, rect, unused_mode, unused_state):
        painter.fillRect(rect, QColor(self.color))
        
        
class ColorButton (QPushButton):
    color_changed = Signal(str)
    
    def __init__(self, replace_button, **kwargs):
        self._icon = ColorIconEngine()
        parent = replace_button.parentWidget()
        super().__init__(QIcon(self._icon), '', parent, **kwargs)
        
        height = self.iconSize().height()
        self.setIconSize(QSize(height * self.width() // self.height(), height))
        self.setSizePolicy(replace_button.sizePolicy())
        self.setObjectName(replace_button.objectName())
        
        layout = replace_button.parentWidget().layout()
        index = layout.indexOf(replace_button)
        position = layout.getItemPosition(index)
        layout.removeWidget(replace_button)
        layout.addWidget(self, *position)
        replace_button.deleteLater()
        self.clicked.connect(self.on_clicked)
        
    def set_color(self, color):
        self._icon.color = color
        self.update()
        
    def get_color(self):
        return self._icon.color
        
    def on_clicked(self):
        dialog = QColorDialog(self)
        dialog.setCurrentColor(QColor(self.get_color()))
        if dialog.exec_() == QDialog.Accepted:
            color = dialog.currentColor().name()
            self.set_color(color)
            self.color_changed.emit(color)
            
        
class ShortcutEditor (QLabel):
    key_pressed = Signal()
    
    def __init__(self, **kwargs):
        super().__init__(text=_('Press a key …'), **kwargs)
        
        self.setFocusPolicy(Qt.StrongFocus)
        self.setAutoFillBackground(True)
        self.key = None
        
    SAFE_MODIFIER_MASK = Qt.ShiftModifier | Qt.ControlModifier
    IGNORE_KEYS = [Qt.Key_Shift, Qt.Key_Control, Qt.Key_Meta, Qt.Key_Alt, Qt.Key_AltGr,
                   Qt.Key_CapsLock, Qt.Key_NumLock, Qt.Key_ScrollLock]
        
    def keyPressEvent(self, event):
        if event.key() in self.IGNORE_KEYS or event.count() != 1:
            return QLabel.keyPressEvent(self, event)
        mod = event.modifiers() & self.SAFE_MODIFIER_MASK
        key = QKeySequence(event.key() | int(mod)).toString().split('+')
        if  event.modifiers() & Qt.KeypadModifier:
            key.insert(-1, 'KP')
        self.key = '+'.join(key)
        self.key_pressed.emit()
        
        
class ShortcutDelegate (QStyledItemDelegate):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        
    def createEditor(self, parent, unused_option, unused_index):
        editor = ShortcutEditor(parent=parent)
        editor.key_pressed.connect(self.on_editor_key_pressed)
        return editor
        
    def setEditorData(self, editor, index):
        pass
        
    def setModelData(self, editor, model, index):
        if editor.key is not None:
            model.setData(index, editor.key, Qt.DisplayRole)
            
    def on_editor_key_pressed(self):
        editor = self.sender()
        self.commitData.emit(editor)
        self.closeEditor.emit(editor, QAbstractItemDelegate.NoHint)
        
        
class PreferencesDialog (Dialog):
    sample_buffers = 0
        
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        
        self.ui = UI(self, 'preferences.ui')
        from .ui.preferences import retranslate
        self.ui = retranslate(self)
        
        self.ui.button_animspeed_reset.setIcon(QIcon.fromTheme('edit-clear'))
        self.ui.button_shader_reset.setIcon(QIcon.fromTheme('edit-clear'))
        self.ui.button_antialiasing_reset.setIcon(QIcon.fromTheme('edit-clear'))
        self.ui.button_mirror_faces_reset.setIcon(QIcon.fromTheme('edit-clear'))
        self.ui.button_movekey_add.setIcon(QIcon.fromTheme('list-add'))
        self.ui.button_movekey_remove.setIcon(QIcon.fromTheme('list-remove'))
        self.ui.button_movekey_reset.setIcon(QIcon.fromTheme('document-revert'))
        self.ui.button_color_reset.setIcon(QIcon.fromTheme('edit-clear'))
        self.ui.button_image_reset.setIcon(QIcon.fromTheme('edit-clear'))
        self.ui.button_background_color_reset.setIcon(QIcon.fromTheme('edit-clear'))
        self.ui.button_mousemode_quad.setIcon(QIcon(os.path.join(config.UI_DIR, 'qt', 'mousemode-quad.png')))
        self.ui.button_mousemode_ext.setIcon(QIcon(os.path.join(config.UI_DIR, 'qt', 'mousemode-ext.png')))
        
        self.ui.buttonBox.button(QDialogButtonBox.Close).setDefault(True)
        self.ui.label_needs_restarted.setVisible(False)
        
        # graphic tab
        self.ui.slider_animspeed.setValue(settings.draw.speed)
        self.ui.slider_animspeed.setRange(*settings.draw.speed_range)
        self.bind('draw.speed', self.ui.slider_animspeed, 'value', 'setValue', 'valueChanged')
        self.bind_reset('draw.speed', self.ui.button_animspeed_reset)
        
        shader_names = {'lighting': _('Lighting'), 'simple': _('Simple')}
        for nick in settings.draw.shader_range:
            self.ui.combobox_shader.addItem(shader_names.get(nick, nick), nick)
        self.ui.combobox_shader.setCurrentIndex(settings.draw.shader)
        self.bind('draw.shader', self.ui.combobox_shader,
                                  'currentIndex', 'setCurrentIndex', 'currentIndexChanged')
        self.bind_reset('draw.shader', self.ui.button_shader_reset)
        
        for text in settings.draw.samples_range:
            self.ui.combobox_samples.addItem(_(text), text)
        self.ui.combobox_samples.setCurrentIndex(settings.draw.samples)
        self.bind('draw.samples', self.ui.combobox_samples,
                                  'currentIndex', 'setCurrentIndex', 'currentIndexChanged')
        self.bind_reset('draw.samples', self.ui.button_antialiasing_reset)
        
        self.ui.spinbox_mirror_faces.setRange(*settings.draw.mirror_distance_range)
        def set_mirror_faces(checked):
            self.ui.checkbox_mirror_faces.setChecked(checked)
            self.ui.spinbox_mirror_faces.setEnabled(checked)
        self.bind('draw.mirror_faces', self.ui.checkbox_mirror_faces, 'isChecked', set_mirror_faces, 'toggled')
        self.bind_reset('draw.mirror_faces', self.ui.button_mirror_faces_reset)
        self.bind('draw.mirror_distance', self.ui.spinbox_mirror_faces, 'value', 'setValue', 'valueChanged')
        self.bind_reset('draw.mirror_distance', self.ui.button_mirror_faces_reset)
        
        html_text = '<html><head/><body><p><span style=" color:#aa0000;">{}</span></p></body></html>'
        html_text = html_text.format(html.escape(_('The program needs to be restarted for the changes to take effect.')))
        self.ui.label_needs_restarted.setText(html_text)
        
        # mouse tab
        def set_selection_mode(unused_mode):
            if settings.draw.selection_nick == 'quadrant':
                self.ui.button_mousemode_quad.setChecked(True)
            elif settings.draw.selection_nick == 'simple':
                self.ui.button_mousemode_ext.setChecked(True)
        self.bind('draw.selection', None, None, set_selection_mode, None)
        
        # keys tab
        self.liststore_movekeys = QStandardItemModel(self)
        self.fill_liststore_movekeys()
        self.ui.listview_movekeys.setModel(self.liststore_movekeys)
        self.liststore_movekeys.itemChanged.connect(self.on_liststore_movekeys_itemChanged)
        self.shortcut_delegate = ShortcutDelegate(parent=self.ui.listview_movekeys)
        self.ui.listview_movekeys.setItemDelegateForColumn(1, self.shortcut_delegate)
        
        # theme tab
        location = QStandardPaths.standardLocations(QStandardPaths.PicturesLocation)
        if not location:
            location = QStandardPaths.standardLocations(QStandardPaths.HomeLocation)
            if not location:
                location = ['']
        self.image_dirname = location[0]
        
        self.button_color = ColorButton(self.ui.button_color)
        self.setTabOrder(self.ui.listview_faces, self.button_color)
        self.button_color.color_changed.connect(self.on_button_color_color_changed)
        self.button_background_color = ColorButton(self.ui.button_background_color)
        self.setTabOrder(self.ui.radiobutton_mosaic, self.button_background_color)
        
        # Only a single color, no picture or pattern
        self.stockfiles = ['']
        self.ui.combobox_image.addItem(_('plain'), '')
        for filename, icon in Theme.textures.get_icons():
            self.stockfiles.append(filename)
            self.ui.combobox_image.addItem(icon, '', filename)
        self.ui.combobox_image.addItem(_('select …'), '/')
        
        self.bind_reset_item('theme.faces.{}.color', self.ui.button_color_reset)
        self.bind_reset_item('theme.faces.{}.image', self.ui.button_image_reset)
        self.bind('theme.bgcolor', self.button_background_color, 'get_color', 'set_color', 'color_changed')
        self.bind_reset('theme.bgcolor', self.ui.button_background_color_reset)
        
        self.facenames = Model.cache_index['facenames']
        self.liststore_faces = QStandardItemModel()
        self.ui.listview_faces.setModel(self.liststore_faces)
        self.ui.listview_faces.selectionModel().currentChanged.connect(self.on_listview_faces_currentChanged)
        self.fill_face_selector()
        
    def fill_face_selector(self):
        for i, (facekey, facename) in enumerate(self.facenames):
            self.liststore_faces.appendRow((QStandardItem(i), QStandardItem(_(facename))))
            filename = settings.theme.faces[facekey].image
            if filename.startswith('/'):
                self.image_dirname = os.path.dirname(filename)
        self.ui.listview_faces.setModelColumn(1)
        #XXX: workaround, listview_faces should automatically set to the correct width
        fm = QFontMetrics(self.ui.listview_faces.font())
        width = max(fm.width(_(fn)) for fk, fn in self.facenames) + 8
        self.ui.listview_faces.setMaximumWidth(width)
        
        active_face = 0
        self.current_facekey = self.facenames[active_face][0]
        index = self.liststore_faces.index(active_face, 1)
        self.ui.listview_faces.setCurrentIndex(index)
        
    def fill_liststore_movekeys(self):
        for move, key in settings.draw.accels:
            self.liststore_movekeys.appendRow([QStandardItem(move), QStandardItem(key)])
        self.liststore_movekeys.setHeaderData(0, Qt.Horizontal, _('Move'))
        self.liststore_movekeys.setHeaderData(1, Qt.Horizontal, _('Key'))
            
    def bind_reset_item(self, settings_key, button):
        def on_clicked():
            delattr(settings, settings_key.format(self.current_facekey))
        button.clicked.connect(on_clicked)
        
    @ staticmethod
    def _accel_mods_to_str(accel_mods):
        accel_str = ''
        for a in accel_mods.value_nicks:
            if accel_str:
                accel_str += '+'
            if a.endswith('-mask'):
                a = a[:-5]
            accel_str += a
        return accel_str
        
    def set_imagefile(self, imagefile):
        index_icon = len(self.stockfiles)
        if imagefile.startswith('/'):
            index = index_icon
            icon = QIcon(imagefile)
        else:
            try:
                index = self.stockfiles.index(imagefile)
            except ValueError:
                index = 0
            icon = QIcon()
        self.ui.combobox_image.setItemIcon(index_icon, icon)
        self.ui.combobox_image.setCurrentIndex(index)
        
    def on_settings_changed(self, key):
        Dialog.on_settings_changed(self, key)
        if self._ignore_changed:
            return
        self._ignore_changed = True
        if key == 'draw.samples':
            visible = (self.sample_buffers != 2**settings.draw.samples > 1)
            self.ui.label_needs_restarted.setVisible(visible)
        elif key == 'draw.accels':
            self.liststore_movekeys.clear()
            self.fill_liststore_movekeys()
        elif key == 'theme.faces.{}.color'.format(self.current_facekey):
            self.button_color.set_color(settings.theme.faces[self.current_facekey].color)
        elif key == 'theme.faces.{}.image'.format(self.current_facekey):
            self.set_imagefile(settings.theme.faces[self.current_facekey].image)
        # Not needed:
        #elif key == 'theme.faces.{}.mode'.format(self.current_facekey):
        self._ignore_changed = False
        
    ###
    
    @Slot(bool)
    def on_checkbox_mirror_faces_toggled(self, checked):
        self.ui.spinbox_mirror_faces.setEnabled(checked)
        
    ### mouse handlers ###
    
    def set_mousemode(self, checked, mode):
        if self._ignore_changed:
            return
        if checked:
            self._ignore_changed = True
            settings.draw.selection_nick = mode
            self._ignore_changed = False
            
    @Slot(bool)
    def on_button_mousemode_quad_toggled(self, checked):
        self.set_mousemode(checked, 'quadrant')
        
    @Slot(bool)
    def on_button_mousemode_ext_toggled(self, checked):
        self.set_mousemode(checked, 'simple')
        
    ### key handlers ###
    
    def get_move_key_list(self):
        move_keys = []
        for i in range(self.liststore_movekeys.rowCount()):
            move, key = [self.liststore_movekeys.item(i, j).data(Qt.DisplayRole) for j in (0, 1)]
            move_keys.append((move, key))
        return move_keys
            
    @Slot()
    def on_button_movekey_add_clicked(self):
        row = self.ui.listview_movekeys.currentIndex().row()
        self._ignore_changed = True
        self.liststore_movekeys.insertRow(row, (QStandardItem(''), QStandardItem('')))
        index = self.liststore_movekeys.index(row, 0)
        self.ui.listview_movekeys.setCurrentIndex(index)
        self.ui.listview_movekeys.edit(index)
        self._ignore_changed = False
        
    @Slot()
    def on_button_movekey_remove_clicked(self):
        row = self.ui.listview_movekeys.currentIndex().row()
        self._ignore_changed = True
        self.liststore_movekeys.takeRow(row)
        settings.draw.accels = self.get_move_key_list()
        self._ignore_changed = False
        
    @Slot()
    def on_button_movekey_reset_clicked(self):  # pylint: disable=R0201
        del settings.draw.accels
        
    def on_liststore_movekeys_itemChanged(self, unused_item):
        self._ignore_changed = True
        settings.draw.accels = self.get_move_key_list()
        self._ignore_changed = False
        
    ### appearance handlers ###
    
    def on_listview_faces_currentChanged(self, current):
        active_face = current.row()
        self.current_facekey = self.facenames[active_face][0]
        self._ignore_changed = True
        self.button_color.set_color(settings.theme.faces[self.current_facekey].color)
        self.set_imagefile(settings.theme.faces[self.current_facekey].image)
        imagemode = settings.theme.faces[self.current_facekey].mode_nick
        if imagemode == 'tiled':
            self.ui.radiobutton_tiled.setChecked(True)
        elif imagemode == 'mosaic':
            self.ui.radiobutton_mosaic.setChecked(True)
        self._ignore_changed = False
        
    def on_button_color_color_changed(self, color):
        if self._ignore_changed:
            return
        self._ignore_changed = True
        settings.theme.faces[self.current_facekey].color = color
        self._ignore_changed = False
        
    @Slot(int)
    def on_combobox_image_activated(self, index):
        if self._ignore_changed:
            return
        try:
            filename = self.stockfiles[index]
        except IndexError:
            filename = QFileDialog.getOpenFileName(self, _("Open Image"), self.image_dirname)
            if isinstance(filename, (tuple, list)):
                filename = filename[0]
            if filename == '':
                # canceled, set the old image
                filename = settings.theme.faces[self.current_facekey].image
                self.set_imagefile(filename)
            else:
                self.image_dirname = os.path.dirname(filename)
        self._ignore_changed = True
        settings.theme.faces[self.current_facekey].image = filename
        self._ignore_changed = False
        
    @Slot(bool)
    def on_radiobutton_tiled_toggled(self, checked):
        self.set_imagemode(checked, 'tiled')
    @Slot(bool)
    def on_radiobutton_mosaic_toggled(self, checked):
        self.set_imagemode(checked, 'mosaic')
        
    def set_imagemode(self, checked, mode):
        if self._ignore_changed:
            return
        if checked:
            self._ignore_changed = True
            settings.theme.faces[self.current_facekey].mode_nick = mode
            self._ignore_changed = False
            
        
class SelectModelDialog (Dialog):
    response_ok = Signal(str, tuple)
    
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        
        self.ui = UI(self, 'model.ui')
        from .ui.model import retranslate
        retranslate(self)
        
        self.mtypes = Model.cache_index['types']
        self.modeldefs = [Model.cache_index['type'][mtype] for mtype in self.mtypes]
        mtype_ranges = lambda mtype: tuple((min(vals), max(vals)) for vals in zip(*Model.cache_index['normsize'][mtype].keys()))
        self.sranges = [mtype_ranges(mtype) for mtype in self.mtypes]
        for i, mtype in enumerate(self.mtypes):
            name = self.modeldefs[i]['name']
            self.ui.combobox_model.addItem(_(name), mtype)
        mtypeidx = self.mtypes.index(settings.game.type)
        self.ui.combobox_model.setCurrentIndex(mtypeidx)
        # Hide items after the dialog size is calculated to avoid later resizing
        QTimer.singleShot(0, lambda: self.on_combobox_model_activated(mtypeidx))
        
    @Slot(int)
    def on_combobox_model_activated(self, index):
        mtype = self.mtypes[index]
        size = settings.games[mtype].size
        try:
            size = Model.cache_index['normsize'][mtype][size]
        except KeyError:
            size = self.modeldefs[index]['defaultsize']
        for label, spin, sizename, srange, svalue in zip_longest(
                        (self.ui.label_width, self.ui.label_heigth, self.ui.label_depth),
                        (self.ui.spin_size1, self.ui.spin_size2, self.ui.spin_size3),
                        self.modeldefs[index]['sizenames'],
                        self.sranges[index],
                        size,
                    ):
            if label is None:
                continue
            label.setText(_(sizename) if sizename is not None else '')
            spin.setVisible(sizename is not None)
            if sizename is not None:
                spin.setRange(*srange)
                spin.setValue(svalue)
                
    def on_response(self):
        index = self.ui.combobox_model.currentIndex()
        size_len = len(self.modeldefs[index]['defaultsize'])
        spins = (self.ui.spin_size1, self.ui.spin_size2, self.ui.spin_size3)[:size_len]
        self.response_ok.emit(
                self.mtypes[index],
                tuple(s.value() for s in spins),
                )
        
        
class ProgressDialog (QProgressDialog):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        
        self.canceled_ = False
        self.value_max = 10
        self.value = 0
        self.setWindowModality(Qt.WindowModal)
        self.setMaximum(self.value_max)
        self.setMinimumDuration(0)
        self.setAutoReset(False)
        self.canceled.connect(self.on_canceled)
        
    def on_canceled(self):
        self.canceled_ = True
        self.setLabelText(_('Canceling operation, please wait'))
        
    def tick(self, step, message=None, value_max=None):
        if not self.isVisible():
            self.show()
        if message is not None:
            self.setLabelText(message)
        if value_max is not None:
            self.value_max = value_max
            self.value = 0
            self.setMaximum(value_max)
        if step < 0 or self.value > self.value_max:
            self.setValue(0)
            self.setMaximum(0)
        else:
            self.setValue(self.value)
            self.value += step
        return self.canceled_
        
    def done(self):
        self.canceled_ = False
        self.reset()
        
        
class HelpDialog (Dialog):
    
    helpstrings = [
            # The next strings form the text in the help dialog
            _('Using the mouse to rotate the cube'),
            _('Position the mouse cursor over the puzzle and you will see an arrow '
              'that gives you a hint in which direction the slice under the mouse cursor will be rotated.'),
            _('The left mouse button rotates a single slice of the cube in the direction of the arrow.'),
            _('The right mouse button rotates a single slice of the cube against the direction of the arrow.'),
            _('To rotate the whole cube instead of a single slice press the Ctrl key together with the mouse button.'),
            
            _('Using the keyboard to rotate the cube'),
            _('Make sure the keyboard focus is on the cube area (e.g. click on the background of the cube). '
              'The keys can be configured in the preferences dialog, the default is:'),
            _('Moves the left, right, upper, down, front or back slice clockwise.'),
            _('Moves a slice couterclockwise.'),
            _('Moves the whole cube.'),
            
            _('Other keys and buttons'),
            _('Mouse wheel – Zoom in/out'),
            _('Arrow keys, Left mouse button on the background – Changes the direction of looking at the cube.'),
            _('Moves keyboard focus to the sequence editor above the cube area '
              'where you can edit the move sequence in the notation described below. '
              'Hit enter when done.'),
            
            _('Notation for moves'),
            _('All moves, however they are made, are displayed progressively above the cube area:'),
            _('Moves the left, right, upper, down, front or back slice clockwise.'),
            _('Moves a slice couterclockwise.'),
            _('Moves the whole cube.'),
            _('Moves the first, second or third slice from left clockwise. '
              'The allowed numbers are in the range from 1 to the count of parallel slices. '
              '"l1" is always the same as "l" '
              'and for the classic 3×3×3-Cube "l2" is the same as "r2-" and "l3" is the same as "r-".'),
            _('You can use a space to separate groups of moves.'),
        ]
    helpformat = '''
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd">
<html>
<head>
<meta name="qrichtext" content="1" />
<style type="text/css">p, li {{ white-space: pre-wrap; }}</style>
</head>

<body>

<h3>{}</h3>
<p>{}</p>
<ul>
<li>{}</li>
<li>{}</li>
<li>{}</li>
</ul>

<h3>{}</h3>
<p>{}</p>
<ul>
<li>4,6,8,2,5,0 – {}</li>
<li>Shift+4, … – {}</li>
<li>Ctrl+4, … – {}</li>
</ul>

<h3>{}</h3>
<ul>
<li>{}</li>
<li>{}</li>
<li>Ctrl+L – {}</li>
</ul>

<h3>{}</h3>
<p>{}</p>
<ul>
<li>l, r, u, d, f, b – {}</li>
<li>l-, r-, u-, d-, f-, b- – {}</li>
<li>L, R, U, D, F, B – {}</li>
<li>l1, l2, l3 – {}</li>
<li>{}</li>
</ul>

</body></html>
    '''
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        
        self.ui = UI(self, 'help.ui')
        from .ui.help import retranslate
        self.ui = retranslate(self)
        
        helpstrings = [html.escape(s) for s in self.helpstrings]
        helptext = self.helpformat.format(*helpstrings)
        self.ui.text_help.setHtml(helptext)
        
        
def linkedtext_to_html(text):
    html = QTextDocumentFragment.fromPlainText(text).toHtml()
    html = re.sub(r'&lt;((?:http:|https:|text:).*?)\|&gt;', r'<a href="\1">', html)
    html = re.sub(r'&lt;\|&gt;', r'</a>', html)
    return re.sub(r'&lt;((?:http:|https:).*?)&gt;', r'&lt;<a href="\1">\1</a>&gt;', html)
    
class UI:
    def __init__(self, toplevel, filename):
        self._toplevel = toplevel
        from PyQt5 import uic
        uic.loadUi(os.path.join(config.UI_DIR, 'qt', filename), toplevel)
    def __getattr__(self, attrname):
        if attrname[0] == '_':
            raise AttributeError('{!r} object has no attribute {!r}'.format('UI', attrname))
        else:
            return self._toplevel.findChild(QObject, attrname)
            
        
class AboutDialog (QDialog):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        
        self.about = UI(self, 'about.ui')
        from .ui.about import retranslate
        retranslate(self)
        
        self.fill_header()
        self.fill_about_tab()
        self.fill_feedback_tab()
        self.fill_translation_tab()
        self.fill_license_tab()
        
        self.index_tab_about = self.about.tab_widget.indexOf(self.about.tab_about)
        self.index_tab_license = self.about.tab_widget.indexOf(self.about.tab_license)
        
        # About tab animation
        self.scrollbar = self.about.text_translators.verticalScrollBar()
        self.animation = QPropertyAnimation(self.scrollbar, 'value')
        self.animation.setLoopCount(-1)
        
    def fill_header(self):
        pixmap = QPixmap(config.APPICON_FILE)
        self.about.label_icon.setPixmap(pixmap)
        self.about.label_appname.setText(_(config.APPNAME))
        self.about.label_version.setText(config.VERSION)
        self.about.label_description.setText(_(config.SHORT_DESCRIPTION))
        
    def fill_about_tab(self):
        self.about.label_copyright.setText(config.COPYRIGHT)
        html_text = '<html><head/><body><p><a href="{}">{}</a></p></body></html>'.format(
                        config.WEBSITE, _('Pybik project website'))
        self.about.label_website.setText(html_text)
        html_template = '''<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd">
<html><head><meta name="qrichtext" content="1" /><style type="text/css">
p, li {{ white-space: pre-wrap; }}
</style></head>
<body>{}</body></html>'''
        html_p_template = '<p align="center">{}</p>'
        html_language_template = '<span style=" font-weight:600;">{}</span>'
        html_person_template = '<a href="{}">{}</a>'
        html_p_items = []
        from .translators import translators
        try:
            import icu
        except ImportError:
            print('PyICU is not installed')
            langname_from_code = lambda code, name: name
        else:
            def langname_from_code(code, name):
                iculocale = icu.Locale.createFromName(code)
                lang = iculocale.getLanguage()
                if icu.Locale.createFromName(lang).getDisplayName() == lang:
                    return name
                return str(iculocale.getDisplayName()) or name
        import locale
        sortfunc = lambda v: locale.strxfrm(v[0])
        def gentranslators():
            for language, langcode, persons in translators:
                language = langname_from_code(langcode, language)
                yield language, persons
        for language, persons in sorted(gentranslators(), key=sortfunc):
            language = html.escape(language)
            html_items = [html_language_template.format(language)]
            for name, link in sorted(persons, key=sortfunc):
                name = html.escape(name)
                html_items.append(html_person_template.format(link, name))
            html_p_items.append(html_p_template.format('<br/>'.join(html_items)))
        html_text = html_template.format(''.join(html_p_items))
        self.about.text_translators.setHtml(html_text)
        qdesktopservices_openurl = QDesktopServices.openUrl
        self.about.text_translators.anchorClicked.connect(qdesktopservices_openurl)
        self.about.text_translators.viewport().installEventFilter(self)
        
    def fill_feedback_tab(self):
        html = linkedtext_to_html(config.get_filebug_text())
        self.about.label_feedback.setText(html)
        
    def fill_translation_tab(self):
        html = linkedtext_to_html(_(config.TRANSLATION_TEXT))
        self.about.label_translation.setText(html)
        
    def fill_license_tab(self):
        self.about.text_license_short.hide()
        self.about.text_license_full.hide()
        html = linkedtext_to_html('\n\n'.join((_(config.LICENSE_INFO), _(config.LICENSE_FURTHER))))
        self.about.text_license_short.setHtml(html)
        try:
            with open(config.LICENSE_FILE, 'rt', encoding='utf-8') as license_file:
                text = license_file.read()
        except Exception as e:
            print('Unable to find license text:', e)
            text = _(config.LICENSE_NOT_FOUND)
            self.about.text_license_full.setLineWrapMode(QTextEdit.WidgetWidth)
        html = linkedtext_to_html(text)
        self.about.text_license_full.setHtml(html)
        self.about.tab_widget.currentChanged.connect(self._on_tab_widget_currentChanged)
        self.about.text_license_short.anchorClicked.connect(self._on_text_license_anchorClicked)
        
    def update_animation(self):
        smin = self.scrollbar.minimum()
        smax = self.scrollbar.maximum()
        if smax <= smin:
            return
        self.animation.setDuration((smax-smin) * 40)
        self.animation.setKeyValueAt(0., smin)
        self.animation.setKeyValueAt(0.04, smin)
        self.animation.setKeyValueAt(0.50, smax)
        self.animation.setKeyValueAt(0.54, smax)
        self.animation.setKeyValueAt(1., smin)
        
    def showEvent(self, unused_event):
        if self.animation.state() == QAbstractAnimation.Stopped:
            self.update_animation()
            self.scrollbar.hide()
            self.animation.start()
            
    def resizeEvent(self, unused_event):
        self.update_animation()
        
    def eventFilter(self, unused_obj, event):
        #assert obj == self.about.text_translators.viewport()
        if event.type() in [QEvent.MouseButtonPress, QEvent.Wheel]:
            self.animation.pause()
            self.scrollbar.show()
        return False
        
    def _on_tab_widget_currentChanged(self, index):
        if index == self.index_tab_about:
            self.animation.resume()
            self.scrollbar.hide()
        else:
            self.animation.pause()
            self.scrollbar.show()
        if index == self.index_tab_license:
            self.about.text_license_short.setVisible(True)
            self.about.text_license_full.setVisible(False)
        
    def _on_text_license_anchorClicked(self, url):
        if url.toString() == 'text:FULL_LICENSE_TEXT':
            self.about.text_license_short.setVisible(False)
            self.about.text_license_full.setVisible(True)
        else:
            QDesktopServices.openUrl(url)
            
    def run(self):
        self.exec_()
        self.deleteLater()
        

