from PyQt5.QtWidgets import QWidget, QLabel
from PyQt5.QtCore import QTimer
from PyQt5.QtGui import QColor, QPalette, QIcon, QPixmap
from PyQt5.QtCore import pyqtSlot, Qt

from ui.ui_prompt import Ui_Prompt

from settings import Settings
from ui.common import change_color, string_abbrev, change_point_size

import logging
logger = logging.getLogger('prompt')


class Logo(QLabel):
    def __init__(self, icon, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.setText("")
        pixmap = QPixmap(icon)
        self.setPixmap(pixmap)
        self.setScaledContents(True)
        self.show()
        self.ratio = pixmap.width() / pixmap.height()

    def resize(self, parent):
        h = int(parent.height() / 3)
        w_p = parent.width()
        self.parent().setFixedSize(w_p, h)
        # Reduce the log width to use the ratio to show it smaller but set as limit
        # the parent width
        #w = 200 if w_p < 200 else (w_p - 200)
        self.setFixedSize(w_p, h) #, int(w/ self.ratio))
        # Center the logo to the parent
        offset_x = int(self.parent().width() / 2 - self.width() / 2)
        self.move(offset_x, self.pos().y())

        #parent.setFixedSize(parent.width(), parent.height() - h)
        print("logo", parent.size(), self.parent().size(), self.size())
        self.__parent = parent

    def mousePressEvent(self, event):
        self.resize(self.__parent)


class _Prompt(QWidget, Ui_Prompt):
    def __init__(self, panel, *args, **kwargs):
        QWidget.__init__(self, *args, **kwargs)
        Ui_Prompt.setupUi(self, self)
        panel.signalPoints.connect(self.cb_points)
        panel.signalSenshu.connect(self.cb_senshu)
        panel.signalPenalty.connect(self.cb_penalty)
        panel.signalTatami.connect(self.cb_tatami)
        panel.signalTimer.connect(self.cb_timer)
        panel.signalFightData.connect(self.cb_data)
        panel.signalWinnerAnimation.connect(self.cb_animation)
        panel.signalCleanup.connect(self.cleanup)

        #self.cleanup()
        self.setWindowTitle('Kumite App - Panel')
        self.setWindowIcon(QIcon(":images/logo.png"))
        self.CategoryLabel.alignCenter()
        self.ModalityLabel.alignCenter()
        self.TatamiLabel.alignCenter()
        self.TimeLabel.alignCenter()
        self.AkaPointsLabel.alignCenter()
        self.AoPointsLabel.alignCenter()

        from ui.widgets import PromptLabel
        self.__labels = self.findChildren(PromptLabel)
        logger.debug('Found total labels %i' % len(self.__labels))

        #self.TatamiLabel.mousePressEvent = self.__debug

        # Add logo widget
        self.logo = Logo(":/images/logo-warmitec.png", parent=self.LogoWidget)

        self.AoPointsLabel.label.setAlignment(Qt.AlignCenter|Qt.AlignRight)
        self.AkaPointsLabel.label.setAlignment(Qt.AlignCenter|Qt.AlignRight)
        #self.AkaMemberLabel.setMaxWidth()
        self.cleanup(True)

    def __debug(self, *args, **kwargs):
        w = self.ch1_aka
        self.__penalty_toggle(w, False)

    def __penalty_toggle(self, widget, on_off):
        pal = widget.palette()
        if on_off:
            widget.setAutoFillBackground(True)
            pal.setColor(QPalette.Window, QColor(255,255,255));
            pal.setColor(QPalette.WindowText, QColor(0,0,0)); # For now just set black as text color
        else:
            pal.setColor(QPalette.WindowText, QColor(255,255,255));
            widget.setAutoFillBackground(False)

        widget.setPalette(pal)

    @pyqtSlot(str, object)
    def cb_load_settings(self):
        logger.info('Loading settings to widgets')
        for e in Settings().prompt.items():
            self.cb_refresh(e.name(), e.get())

    @pyqtSlot(str, object)
    def cb_refresh(self, group, value):
        if group == 'team':
            self.AkaLabel.setPointSize(value)
            self.AoLabel.setPointSize(value)
        elif group == 'category':
            self.CategoryLabel.setPointSize(value)
        elif group == 'modality':
            self.ModalityLabel.setPointSize(value)
        elif group == 'tatami':
            self.TatamiLabel.setPointSize(value, txt_fmt='12')
            self.TatamiLabel.label.setAlignment(Qt.AlignTop|Qt.AlignHCenter)
            change_point_size(self.labelTatami, max(30, value - 150), family="BankGothic Md BT")
            self.logo.resize(self.TatamiLabel)
        elif group == 'point':
            self.AkaPointsLabel.setPointSize(value, resize='w', txt_fmt='00', factor_w=1.1)
            self.AoPointsLabel.setPointSize(value, resize='w', txt_fmt='00', factor_w=1.1)
        elif group == 'time':
            self.TimeLabel.setPointSize(value)
        elif group == 'penalty':
            self.PenaltyAoLabel.setPointSize(value, resize='*')
            self.PenaltyAkaLabel.setPointSize(value, resize='*')
            self.__resize_faults(value)
        elif group == 'member':
            self.AkaMemberLabel.setPointSize(value, resize='h')
            self.AoMemberLabel.setPointSize(value, resize='h')
        elif group == 'senshu':
            change_point_size(self.SenshuAkaLabel, value, family="BankGothic Md BT")
            change_point_size(self.SenshuAoLabel, value, family="BankGothic Md BT")
        else:
            raise RuntimeError('Unknown label group %s' % group)

    def __resize_faults(self, sz):
        for w in self.fault_widgets():
            font = w.font()
            font.setPointSize(sz - 4)
            w.setFont(font)

    def mousePressEvent(self, event):
        pass

    def cb_animation(self, team, off):
        if team == 'aka':
            color = Settings().panel['aka_off' if off else 'aka'].get()
            widget = self.frame_aka
        else:
            widget = self.frame_ao
            color = Settings().panel['ao_off' if off else 'ao'].get()

        change_color(widget, color)

    def resizeEvent(self, event):
        logger.debug("Resized to %s" % repr(self.size()))
        self.refresh()
        self.setFixedSize(self.width(), self.height())
        self.__resize_flags()

    def __resize_flags(self):
        # -- Switch the flags height to the same height of the team labels
        reference = self.AkaLabel.label
        h = int(reference.height() * 0.7)
        logger.debug("Resized flags to %ix%i" % (h, h))
        self.FlagAo.setFixedSize(h, h)
        self.FlagAka.setFixedSize(h, h)

    def refresh(self):
        for l in self.__labels: l.refresh()
        self.logo.resize(self.TatamiLabel)
        self.__resize_flags()
        self.update()

    def fault_widgets(self):
        names = ['ch1_aka', 'ch2_aka', 'ch3_aka', 'h_aka', 'hc_aka',
                'ch1_ao', 'ch2_ao', 'ch3_ao', 'h_ao', 'hc_ao']
        return [getattr(self, n) for n in names]

    def cb_points(self, team, value):
        if team == 'ao':
            self.AoPointsLabel.setText(str(value))
        else:
            self.AkaPointsLabel.setText(str(value))

    def cb_tatami(self, value):
        self.TatamiLabel.setText(str(value))

    def cb_senshu(self, team, on):
        if team == 'aka':
            #self.SenshuAkaLabel.setText("SENSHU" if on else "")
            self.SenshuAkaLabel.setVisible(on)
        elif team == 'ao':
            #self.SenshuAoLabel.setText("SENSHU" if on else "")
            self.SenshuAoLabel.setVisible(on)

    def cb_penalty(self, widget_name, team, actives):
        logger.debug(f"New penalty {widget_name} team {team} actives {actives}")

        if team == 'aka':
            widgets = [self.ch1_aka, self.ch2_aka, self.ch3_aka, self.hc_aka, self.h_aka]
        else:
            widgets = [self.ch1_ao, self.ch2_ao, self.ch3_ao, self.hc_ao, self.h_ao]

        for index in range(0, 5):
            self.__penalty_toggle(widgets[index], actives[index])

    def cb_timer(self, value, string):
        self.TimeLabel.setText(string)

    @pyqtSlot(bool)
    def cleanup(self, full):
        logger.info("Cleaning up")
        for w in self.fault_widgets():
            self.__penalty_toggle(w, False)

        self.AkaPointsLabel.setText("0")
        self.AoPointsLabel.setText("0")
        self.cb_animation('aka', False)
        self.cb_animation('ao', False)

        self.cb_senshu("aka", False)
        self.cb_senshu("ao", False)

    def cb_data(self, data):
        logger.debug('Loaded new fight data')
        self.CategoryLabel.setText(data.category)
        self.ModalityLabel.setText(data.modality)
        self.__set_team(self.AkaMemberLabel, *data.aka)
        self.__set_team(self.AoMemberLabel, *data.ao)
        self.__switch_panel(data.modality.lower() == 'kata')

    def __switch_panel(self, is_kata):
        self.PenaltyAkaLabel.setVisible(not is_kata)
        self.PenaltyAoLabel.setVisible(not is_kata)
        for w in self.fault_widgets():
            w.setVisible(not is_kata)

        self.FlagAo.setVisible(is_kata)
        self.FlagAka.setVisible(is_kata)

    def __set_team(self, widget, member, dojo):
        widget.setText(string_abbrev(member, 20) + ' / ' + string_abbrev(dojo, 20))
        # -- Resize the width to the same that is available for the label
        widget.setFixedWidth(self.AkaLabel.width())


class Prompt(object):

    _instance = None

    def __new__(cls, *args, **kwargs):
        if not Prompt._instance:
            Prompt._instance = _Prompt(*args, **kwargs)
        return Prompt._instance
