# 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, Optional

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.widgets.account import AccountWidget
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
        self.main_window: Optional[MainWindow] = None

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

        # subscribe to the event bus
        self.event_bus = EventBus.instance()
        self.event_bus.main_window_shown.connect(self.on_window_shown)
        self.event_bus.user_data_restored.connect(self.on_user_data_restored_event)
        self.event_bus.currency_changed.connect(self.on_currency_changed)
        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
                ),
            )
        )
        self.event_bus.identity_account_changed.connect(
            lambda issuer_account, destination_account: self.thread_manager.start(
                lambda: self.on_identity_account_changed(
                    issuer_account, destination_account
                ),
                lambda: self.on_identity_account_changed_finished(
                    issuer_account, destination_account
                ),
            )
        )
        self.event_bus.profile_account_changed.connect(
            lambda issuer_account, destination_account: self.thread_manager.start(
                lambda: self.on_profile_account_changed(
                    issuer_account, destination_account
                ),
                lambda: self.on_profile_account_changed_finished(
                    issuer_account, destination_account
                ),
            )
        )

    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"))
        self.main_window = MainWindow(self.application)
        self.main_window.show()

        # open welcome window if no accounts
        if self.application.accounts.count() == 0:
            self.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)

    def connect_to_servers_and_fetch_data(self):
        """
        Connect to node, indexer and datapod and fetch data from network
        to update local repository
        :return:
        """
        self.connect_to_node()
        self.connect_to_indexer()
        self.connect_to_datapod()

    def connect_to_node(self):
        """
        Connection to node

        :return:
        """
        self.application.nodes.connect()
        if self.application.connections.node.is_connected():
            self.event_bus.node_connected.emit()
            self.fetch_data_from_network_node()
        else:
            self.event_bus.node_disconnected.emit()

    def connect_to_indexer(self):
        """
        Connection to indexer

        :return:
        """
        self.application.indexers.connect()
        if self.application.connections.indexer.is_connected():
            self.event_bus.indexer_connected.emit()
            self.fetch_data_from_network_indexer()
        else:
            self.event_bus.indexer_disconnected.emit()

    def connect_to_datapod(self):
        """
        Connection to datapod

        :return:
        """
        self.application.datapods.connect()
        if self.application.connections.datapod.is_connected():
            self.event_bus.datapod_connected.emit()
            self.fetch_data_from_network_datapod()
        else:
            self.event_bus.datapod_disconnected.emit()

    def fetch_data_from_network_node(self):
        """
        Fetch data from the network node

        :return:
        """
        self.application.nodes.network_fetch_current_node()
        self.application.currencies.network_update_properties()

        self.application.nodes.network_fetch_endpoints()
        self.application.indexers.network_fetch_endpoints()

        accounts = self.application.accounts.get_list()
        try:
            self.application.accounts.network_update_balances(accounts)
        except Exception as exception:
            logging.exception(exception)

        addresses = [account.address for account in accounts]
        try:
            self.application.identities.network_update_identities(addresses)
        except Exception as exception:
            logging.exception(exception)
        else:
            identity_indice = self.application.identities.list_indice()
            try:
                self.application.smiths.network_update_smiths(identity_indice)
            except Exception as exception:
                logging.exception(exception)
            else:
                self.application.authorities.network_get_all()

        self.application.technical_committee.network_update_members()
        self.application.technical_committee.network_update_proposals()

    def fetch_data_from_network_indexer(self):
        """
        Fetch data from the network indexer

        :return:
        """
        self.application.indexers.network_fetch_current_indexer()

        accounts = self.application.accounts.get_list()
        addresses = [account.address for account in accounts]
        try:
            # update identity names from indexer
            self.application.identities.network_update_identities(addresses)
        except Exception as exception:
            logging.exception(exception)

        for identity in self.application.identities.list():
            self.application.certifications.network_fetch_certifications_for_identity(
                identity.index
            )

        # update identity names for technical committee members from indexer
        self.application.technical_committee.network_update_members()

        # update transfers for all account opened in main window
        for widget in self.main_window.get_tab_widgets_by_class(AccountWidget):
            if isinstance(widget, AccountWidget):
                self.application.transfers.network_fetch_history_for_account(
                    widget.account, widget.history_limit
                )
                self.application.transfers.network_fetch_total_count_for_address(
                    widget.account
                )

    def fetch_data_from_network_datapod(self):
        """
        Fetch data from the network data pod

        :return:
        """
        self.application.datapods.network_fetch_current_datapod()

        for account in self.application.accounts.get_list():
            try:
                self.application.profiles.network_update(account)
            except Exception as exception:
                logging.exception(exception)

    def connect_to_servers_and_fetch_data_finished(self):
        """
        Triggered when all connections are done

        :return:
        """
        self.event_bus.repository_data_updated.emit()
        logging.debug("Network servers data fetch finished....emit signal")

    #########################################
    # EVENT BUS HANDLING
    #########################################
    def on_window_shown(self):
        """
        Triggered when the window is shown

        :return:
        """
        self.thread_manager.start(
            self.connect_to_servers_and_fetch_data,
            self.connect_to_servers_and_fetch_data_finished,
        )

    def on_user_data_restored_event(self):
        """
        Triggered when the user data are restored

        :return:
        """
        self.thread_manager.start(
            self.connect_to_servers_and_fetch_data,
            self.connect_to_servers_and_fetch_data_finished,
        )

    def on_currency_changed(self, current_code_name: str, new_code_name: str):
        """
        Triggered when the currency_changed event is dispatched

        :param current_code_name: Current Currency code name
        :param new_code_name: New Currency code name
        :return:
        """
        # disconnect servers
        self.application.connections.disconnect_all()

        # close current currency
        self.event_bus.currency_closed.emit(current_code_name)

        # change currency in backend
        self.application.select_currency(new_code_name)

        # close current currency
        self.event_bus.currency_opened.emit(new_code_name)

        # async update data from network
        self.thread_manager.start(
            self.connect_to_servers_and_fetch_data,
            self.connect_to_servers_and_fetch_data_finished,
        )

    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 !!!!!!!!!!!!!!!!!!!!!"
        )

    def on_identity_account_changed(
        self, issuer_account: Account, destination_account: Account
    ):
        """
        Triggered when an identity_account_changed event is dispatched

        :param issuer_account: Issuer Account instance
        :param destination_account: Destination Account instance
        :return:
        """
        # wait for a block before getting indexed data
        sleep(self.application.currencies.get_current().block_duration / 1000)

        # update issuer identity (should be None)
        try:
            self.application.identities.network_update_identity(issuer_account.address)
        except Exception as exception:
            logging.exception(exception)

        # update destination identity
        try:
            self.application.identities.network_update_identity(
                destination_account.address
            )
        except Exception as exception:
            logging.exception(exception)

    def on_identity_account_changed_finished(
        self, issuer_account: Account, destination_account: Account
    ):
        """
        Triggered when an identity_account_changed event is finished

        :param issuer_account: Issuer Account instance
        :param destination_account: Destination Account instance
        :return:
        """
        self.event_bus.account_identities_updated.emit(
            [issuer_account, destination_account]
        )
        logging.debug(
            "QMainApplication.on_identity_account_changed_finished account_identities_updated emitted !!!!!!!!!!!!!!!!!!!!!"
        )

    def on_profile_account_changed(
        self, issuer_account: Account, destination_account: Account
    ):
        """
        Triggered when a profile_account_changed event is dispatched

        :param issuer_account: Issuer Account instance
        :param destination_account: Destination Account instance
        :return:
        """
        pass

    def on_profile_account_changed_finished(
        self, issuer_account: Account, destination_account: Account
    ):
        """
        Triggered when on_profile_account_changed event is finished

        :param issuer_account: Issuer Account instance
        :param destination_account: Destination Account instance
        :return:
        """
        self.event_bus.account_profiles_updated.emit(
            [issuer_account, destination_account]
        )
        logging.debug(
            "QMainApplication.on_profile_account_changed_finished account_profiles_updated emitted !!!!!!!!!!!!!!!!!!!!!"
        )
