# -*- coding: UTF-8 -*-
import os
import sys
import yaml
from PySide2 import QtWidgets, QtGui

from ..util.config import SHOT_ASSET, CONFIG_PATH, ICON_PATH


class MainController(QtWidgets.QWidget):
    def __init__(self, *args, **kwargs):
        super(MainController, self).__init__(*args, **kwargs)
        self._main_window = None
        self._main_mixin = None
        self._context = None
        self.show = None
        self.entity = None
        self.sequence = None
        self.setAcceptDrops(True)

    def connect_to_main_mixin(self, mixin):
        """
        Used to connect this controller to the main mixin that's generated by qt designer

        :param object mixin: the object created by qt designer code
        :return: None
        """
        self._main_mixin = mixin

    def connect_to_main_window(self, window):
        """
        Used to connect this controller to the main window

        :param QDialog window: the window that the controller may need access to
        :return: None
        """
        self._main_window = window

    def initialize(self, context):
        """
        Initialize should be called after object creation and calling connect_to_main_mixin and connect_to_main_window

        :param str context: eg 'BHB/shots/bhb101_010_020/anm'
        :return: None
        """

        # First we set up our operating parameters
        self._context = Context(context)

        # register our chinese translation file in the bp.language module.
        language.register_chinese_translation(':ts/zh.qm')

        self.set_show()
        self.set_entity()
        self.set_sequence()
        self.set_step()
        self.set_icon()

    def set_show(self):
        """
        Set show name in show_comboBox area
        :return:
        """
        show_list = list(get_all_shows())
        if len(show_list) != 0:
            self._main_window.show_comboBox.clear()
            self._main_window.show_comboBox.addItems(show_list)

    def set_entity(self):
        """
        Set entity type in entity_comboBox area
        """
        self._main_window.entity_comboBox.clear()
        self._main_window.entity_comboBox.addItems(SHOT_ASSET)

        entity_type = self._main_window.entity_comboBox.currentText()

        # TODO: use slot to change entity_lable text
        if entity_type == 'shot':
            self._main_window.entity_lable.setText(self._main_window.tr("Shot:"))
        else:
            self._main_window.entity_lable.setText(self._main_window.tr("Asset:"))

    def set_sequence(self):
        """
        Set sequence in the sequence_comboBox area
        """
        self.show = self._main_window.show_comboBox.currentText()
        self.entity = self._main_window.entity_comboBox.currentText()
        sequence_list = get_sequences(self.show)
        self._main_window.sequence_comboBox.set_model(sequence_list)
        self._main_window.sequence_comboBox.clear()
        self._main_window.sequence_comboBox.addItems(sequence_list)

    def set_shot(self):
        """
        Set shot in the shot_comboBox area
        """
        self.sequence = self._main_window.sequence_comboBox.currentText()

        shot_list = get_shots(self.show, self.sequence)
        self._main_window.shot_comboBox.clear()
        if len(shot_list) != 1:
            self._main_window.shot_comboBox.set_model(shot_list)
            self._main_window.shot_comboBox.addItems(shot_list)

    def set_step(self):
        """
        Set pipeline step in the task_comboBox area
        """
        self.show = self._main_window.show_comboBox.currentText()
        self.entity = self._main_window.entity_comboBox.currentText()

        if self.show and self.entity:
            step_list = get_steps(self.show, self.entity).keys()
            self._main_window.task_comboBox.clear()
            self._main_window.task_comboBox.set_model(step_list)
            self._main_window.task_comboBox.addItems(step_list)

    def set_user(self):
        """
        Set user name in the user_comboBox area
        """
        self.show = self._main_window.show_comboBox.currentText()
        user_list = get_users(self.show)
        self._main_window.user_comboBox.clear()
        self._main_window.user_comboBox.set_model(user_list)
        self._main_window.user_comboBox.addItems(user_list)

    def set_icon(self):
        """
        Set icon in the icon_field area
        :return:
        """
        tab_item_file = os.path.join(CONFIG_PATH, 'tab_item.yml')
        icon_path_file = os.path.join(CONFIG_PATH, 'icon_path.yml')

        # check if the configuration files exist
        for f in [tab_item_file, icon_path_file]:
            if not os.path.exists(f):
                show_alert(self, u'Missing Configuration File', u'缺少配置文件', u'{}\n doen\'t exist.'.format(f), u'{}\n文件不存在'.format(f))
                sys.exit()

        # load configuration files
        with open(tab_item_file) as t:
            tab_item = yaml.load(t)

        with open(icon_path_file) as i:
            icon_path = yaml.load(i)

        tab_name = {'Artist': self._main_window.artist_tab,
                    'Admin': self._main_window.admin_tab,
                    'Test': self._main_window.test_tab,
                    'Others': self._main_window.others_tab}

        for k, v in tab_item.items():
            for app in v:
                # check if the apps name exist in icon_path configuration file
                if app not in icon_path.keys():
                    show_alert(self, u'Error', u'错误', u'Missing "{}" in\n{}'.format(app, icon_path_file),
                               u'{}不在配置文件中\n{}'.format(app, icon_path_file))
                    sys.exit()

                if icon_path[app]:
                    # check if the tab names exist in tab_name dictionary
                    if k not in tab_name.keys():
                        show_alert(self, u'Error', u'错误', u'Missing "{}" in tab_name'.format(k), u'tab_name中缺少{}'.format(k))
                        sys.exit()

                    tab_name[k].addItem(
                            QtWidgets.QListWidgetItem(QtGui.QIcon(os.path.join(ICON_PATH, icon_path[app])), app))


