# 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 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.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 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),
            )
        )

    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]):
        """
        Triggered when 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 account_balances_updated emited !!!!!!!!!!!!!!!!!!!!!"
        )
