# Copyright 2021 Vincent Texier <vit@free.fr>
#
# This software 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 software 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/>.
import logging
import sys
from pathlib import Path
from time import sleep
from typing import List

from PyQt5.QtCore import QCoreApplication, QLibraryInfo, QLocale, QTranslator
from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import QApplication

from tikka.domains.application import Application
from tikka.domains.config import Config
from tikka.domains.entities.account import Account
from tikka.domains.entities.identity import Identity
from tikka.slots.pyqt.entities.constants import ACCOUNT_TRANSFER_HISTORY_LIMIT
from tikka.slots.pyqt.entities.event_bus import EventBus
from tikka.slots.pyqt.entities.worker import ThreadManager
from tikka.slots.pyqt.windows.main import MainWindow


class PyQtMainApplication:
    """
    PyQtMainApplication class
    """

    def __init__(
        self, application: Application
    ):  # pylint: disable=super-init-not-called
        """
        Init PyQtMainApplication instance

        :param application: Application instance
        """

        self.application = application

        # Async manager
        self.thread_manager: ThreadManager = ThreadManager()

        # subscribe to the event bus
        self.event_bus = EventBus.instance()
        self.event_bus.transfer_sent.connect(
            lambda _accounts: self.thread_manager.start(
                lambda: self.on_transfer_sent(_accounts),
                lambda: self.on_transfer_sent_finished(_accounts),
            )
        )
        self.event_bus.identity_created.connect(
            lambda issuer_identity, identity: self.thread_manager.start(
                lambda: self.on_identity_created(issuer_identity, identity),
                lambda: self.on_identity_created_finished(issuer_identity, identity),
            )
        )
        self.event_bus.identity_confirmed.connect(
            lambda identity: self.thread_manager.start(
                lambda: self.on_identity_confirmed(identity),
                lambda: self.on_identity_confirmed_finished(identity),
            )
        )
        self.event_bus.identity_certified.connect(
            lambda issuer_identity, receiver_identity: self.thread_manager.start(
                lambda: self.on_identity_certified(issuer_identity, receiver_identity),
                lambda: self.on_identity_certified_finished(
                    issuer_identity, receiver_identity
                ),
            )
        )

    def run(self):
        """
        Start PyQt application event loop

        :return:
        """
        qt_application = QApplication(sys.argv)

        self.init_i18n(qt_application)

        # main window
        qt_application.setWindowIcon(QIcon(":/icons/logo"))
        main_window = MainWindow(self.application)
        main_window.show()

        # open welcome window if no accounts
        if self.application.accounts.count() == 0:
            main_window.open_welcome_window()

        # run Qt event loop
        sys.exit(qt_application.exec_())

    def init_i18n(self, qt_application: QApplication):
        """
        Init Locale and translator

        :param qt_application: QApplication instance
        :return:
        """
        # qt builtin locales for filedialog or buttonbox...
        QLocale.setDefault(QLocale(self.application.config.get(Config.LANGUAGE_KEY)))
        translator = QTranslator(qt_application)
        filename = (
            "qtbase_" + self.application.config.get(Config.LANGUAGE_KEY).split("_")[0]
        )
        result = translator.load(
            filename, QLibraryInfo.location(QLibraryInfo.TranslationsPath)
        )
        if result is False:
            raise FileNotFoundError(
                Path(QLibraryInfo.location(QLibraryInfo.TranslationsPath)).joinpath(
                    filename
                )
            )
        QCoreApplication.installTranslator(translator)

    #########################################
    # EVENT BUS HANDLING
    #########################################
    def on_transfer_sent(self, accounts: List[Account]):
        """
        Triggered when a transfer_sent event is dispatched

        :param accounts: List of Account instances
        :return:
        """
        if len(accounts) > 0:
            logging.debug(
                "QMainApplication.on_transfer_sent triggered !!!!!!!!!!!!!!!!!!!!!"
            )
            self.application.accounts.network_update_balances(accounts),

            for account in accounts:
                self.application.transfers.network_fetch_history_for_account(
                    account, ACCOUNT_TRANSFER_HISTORY_LIMIT
                )
                self.application.accounts.network_update_total_transfers_count(account)

    def on_transfer_sent_finished(self, accounts: List[Account]):
        """
        Executed after a transfer_sent event is dispatched

        :param accounts: List of Account instances
        :return:
        """
        self.event_bus.account_balances_updated.emit(accounts)
        logging.debug(
            "QMainApplication.on_transfer_sent_finished account_balances_updated emitted !!!!!!!!!!!!!!!!!!!!!"
        )

    def on_identity_created(self, issuer_identity: Identity, identity: Identity):
        """
        Triggered when an identity_created event is dispatched

        :param issuer_identity: Issuer Identity instance
        :param identity: Created Identity instance
        :return:
        """
        # wait for a block before getting indexed data
        sleep(self.application.currencies.get_current().block_duration / 1000)

        try:
            self.application.certifications.network_fetch_certifications_for_identity(
                issuer_identity.index
            )
        except Exception as exception:
            logging.exception(exception)

        try:
            self.application.certifications.network_fetch_certifications_for_identity(
                identity.index
            )
        except Exception as exception:
            logging.exception(exception)

    def on_identity_created_finished(
        self, issuer_identity: Identity, identity: Identity
    ):
        """
        Executed after an identity_created event is dispatched

        :param issuer_identity: Issuer Identity instance
        :param identity: Created Identity instance
        :return:
        """
        self.event_bus.identities_updated.emit([issuer_identity, identity])
        logging.debug(
            "QMainApplication.on_identity_created_finished identities_updated emitted !!!!!!!!!!!!!!!!!!!!!"
        )

    def on_identity_confirmed(self, identity: Identity):
        """
        Triggered when an identity_confirmed event is dispatched

        :param identity: Confirmed Identity instance
        :return:
        """
        # wait for a block before getting indexed data
        sleep(self.application.currencies.get_current().block_duration / 1000)

        # update identity again to get indexed name
        try:
            self.application.identities.network_update_identity(identity.address)
        except Exception as exception:
            logging.exception(exception)
        # update certifications with name
        try:
            self.application.certifications.network_fetch_certifications_for_identity(
                identity.index
            )
        except Exception as exception:
            logging.exception(exception)

        certifications = self.application.certifications.list(identity.index)
        if len(certifications) > 0:
            # update first certification of identity creator
            try:
                self.application.certifications.network_fetch_certifications_for_identity(
                    certifications[0].issuer_identity_index
                )
            except Exception as exception:
                logging.exception(exception)

    def on_identity_confirmed_finished(self, identity: Identity):
        """
        Executed after an identity_created event is dispatched

            :param identity: Confirmed Identity instance
        :return:
        """
        identities = [identity]
        certifications = self.application.certifications.list(identity.index)
        if len(certifications) > 0:
            identity_creator = self.application.identities.get_by_address(
                certifications[0].issuer_address
            )
            if identity_creator is not None:
                identities.append(identity_creator)

        self.event_bus.identities_updated.emit(identities)
        logging.debug(
            "QMainApplication.on_identity_confirmed_finished identities_updated emitted !!!!!!!!!!!!!!!!!!!!!"
        )

    def on_identity_certified(
        self, issuer_identity: Identity, receiver_identity: Identity
    ):
        """
        Triggered when an identity_certified event is dispatched

        :param issuer_identity: Issuer Identity instance
        :param receiver_identity: Receiver Identity instance
        :return:
        """
        # wait for a block before getting indexed data
        sleep(self.application.currencies.get_current().block_duration / 1000)

        # update receiver identity if status changed
        try:
            self.application.identities.network_update_identity(
                receiver_identity.address
            )
        except Exception as exception:
            logging.exception(exception)

        try:
            self.application.certifications.network_fetch_certifications_for_identity(
                issuer_identity.index
            )
        except Exception as exception:
            logging.exception(exception)

        try:
            self.application.certifications.network_fetch_certifications_for_identity(
                receiver_identity.index
            )
        except Exception as exception:
            logging.exception(exception)

    def on_identity_certified_finished(
        self, issuer_identity: Identity, receiver_identity: Identity
    ):
        """
        Executed after an identity_created event is dispatched

        :param issuer_identity: Issuer Identity instance
        :param receiver_identity: Receiver Identity instance
        :return:
        """
        self.event_bus.identities_updated.emit([issuer_identity, receiver_identity])
        logging.debug(
            "QMainApplication.on_identity_certified_finished identities_updated emitted !!!!!!!!!!!!!!!!!!!!!"
        )
