# 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 datetime import datetime
from typing import Optional

from PyQt5.QtCore import QPoint
from PyQt5.QtWidgets import QApplication, QListView, QMainWindow, QWidget

from tikka.domains.application import Application
from tikka.domains.entities.account import Account, AccountCryptoType
from tikka.domains.entities.constants import TEST_DATA_PATH
from tikka.domains.entities.identity import Certification, Identity, IdentityStatus
from tikka.slots.pyqt.entities.event_bus import EventBus
from tikka.slots.pyqt.entities.worker import ThreadManager
from tikka.slots.pyqt.models.certifications import (
    CertificationItemDelegate,
    CertificationsListModel,
)
from tikka.slots.pyqt.resources.gui.widgets.account_identity_rc import (
    Ui_AccountIdentityWidget,
)
from tikka.slots.pyqt.widgets.account_tabs.identity_certifications_menu import (
    IdentityCertificationsPopupMenu,
)
from tikka.slots.pyqt.windows.identity_certify import IdentityCertifyWindow
from tikka.slots.pyqt.windows.identity_change_account import IdentityChangeAccountWindow
from tikka.slots.pyqt.windows.identity_confirm import IdentityConfirmWindow
from tikka.slots.pyqt.windows.identity_create import IdentityCreateWindow


class AccountIdentityWidget(QWidget, Ui_AccountIdentityWidget):
    """
    AccountIdentityWidget class
    """

    def __init__(
        self,
        application: Application,
        account: Account,
        parent: Optional[QWidget] = None,
    ) -> None:
        """
        Init AccountIdentityWidget instance

        :param application: Application instance
        :param account: Account instance
        :param parent: QWidget instance
        """
        super().__init__(parent=parent)
        self.setupUi(self)

        self.application = application
        self._ = self.application.translator.gettext

        self.event_bus = EventBus.instance()

        self.account: Account = account
        self.identity: Optional[Identity] = self.application.identities.get_by_address(
            self.account.address
        )

        # certifications received
        self.certifications_received_model = CertificationsListModel(
            application,
            self.locale(),
            self.application.repository.certifications.COLUMN_RECEIVER_IDENTITY_INDEX,
        )
        self.certificationsReceivedListView.setModel(self.certifications_received_model)
        self.certificationsReceivedListView.setItemDelegate(CertificationItemDelegate())
        self.certificationsReceivedListView.setResizeMode(QListView.Adjust)

        # certifications issued
        self.certifications_issued_model = CertificationsListModel(
            application,
            self.locale(),
            self.application.repository.certifications.COLUMN_ISSUER_IDENTITY_INDEX,
        )
        self.certificationsIssuedListView.setModel(self.certifications_issued_model)
        self.certificationsIssuedListView.setItemDelegate(CertificationItemDelegate())
        self.certificationsIssuedListView.setResizeMode(QListView.Adjust)

        ##############################
        # ASYNC METHODS
        ##############################
        self.thread_manager: ThreadManager = ThreadManager(self)

        # events
        self.confirmIdentityButton.clicked.connect(
            self.on_confirm_identity_button_clicked
        )
        self.createIdentityButton.clicked.connect(
            self.on_create_identity_button_clicked
        )
        self.certifyIdentityButton.clicked.connect(
            self.on_certify_identity_button_clicked
        )
        self.identityChangeAccountButton.clicked.connect(
            self.on_identity_change_account_button_clicked
        )
        self.certificationsReceivedListView.customContextMenuRequested.connect(
            self.on_received_certifications_context_menu
        )
        self.certificationsIssuedListView.customContextMenuRequested.connect(
            self.on_issued_certifications_context_menu
        )

        self.update_ui()

    def async_refresh_data_from_network(self):
        """
        Triggered when user click on account tab refresh button

        :return:
        """
        self.thread_manager.start(
            self.fetch_certifications_from_network,
            self.on_finished_fetch_certifications_from_network,
        )

    def fetch_certifications_from_network(self):
        """
        Get certifications data from the network

        :return:
        """
        if (
            self.identity is None
            or not self.application.connections.indexer.is_connected()
        ):
            return
        try:
            self.application.certifications.network_fetch_certifications_for_identity(
                self.identity.index
            )
        except Exception as exception:
            logging.exception(exception)

    def on_finished_fetch_certifications_from_network(self):
        """
        Triggered when async request fetch_certifications_from_network is finished

        :return:
        """
        self.update_ui()
        logging.debug(
            "Finished fetch identity certifications %s %s",
            self.account.name,
            self.account.address,
        )

    def update_ui(self):
        """
        Update UI from self.account

        :return:
        """
        # update local data from DB
        self.account = self.application.accounts.get_by_address(self.account.address)
        self.identity = self.application.identities.get_by_address(self.account.address)

        if self.identity is not None:
            self.createIdentityButton.setEnabled(
                self.identity.status == IdentityStatus.MEMBER
                and self.application.connections.node.is_connected()
                and self.application.wallets.exists(self.account.address)
            )
            self.confirmIdentityButton.setEnabled(
                self.identity.status == IdentityStatus.UNCONFIRMED
                and self.application.connections.node.is_connected()
                and self.application.wallets.exists(self.account.address)
            )
            self.certifyIdentityButton.setEnabled(
                self.identity.status == IdentityStatus.MEMBER
                and self.application.connections.node.is_connected()
                and self.application.wallets.exists(self.account.address)
            )
            self.identityChangeAccountButton.setEnabled(
                self.application.connections.node.is_connected()
                and self.application.wallets.exists(self.account.address)
            )
        else:
            self.confirmIdentityButton.setDisabled(True)
            self.createIdentityButton.setDisabled(True)
            self.certifyIdentityButton.setDisabled(True)
            self.identityChangeAccountButton.setDisabled(True)

        self.certifications_issued_model.init_data(
            self.identity.index if self.identity else None
        )
        self.certifications_received_model.init_data(
            self.identity.index if self.identity else None
        )

    def on_received_certifications_context_menu(self, position: QPoint):
        """
        When right button on received certifications listview

        :return:
        """
        # get selected certification
        certification = (
            self.certificationsReceivedListView.currentIndex().internalPointer()
        )
        if certification is not None:
            # display popup menu at click position
            menu = IdentityCertificationsPopupMenu(
                self.application, self.account, certification, self
            )
            menu.exec_(self.certificationsReceivedListView.mapToGlobal(position))

    def on_issued_certifications_context_menu(self, position: QPoint):
        """
        When right button on issued certifications listview

        :return:
        """
        # get selected certification
        certification = (
            self.certificationsIssuedListView.currentIndex().internalPointer()
        )
        if certification is not None:
            # display popup menu at click position
            menu = IdentityCertificationsPopupMenu(
                self.application, self.account, certification, self
            )
            menu.exec_(self.certificationsIssuedListView.mapToGlobal(position))

    def on_confirm_identity_button_clicked(self):
        """
        Triggered when user click on confirm_identity_button

        :return:
        """
        window = IdentityConfirmWindow(self.application, self.account)
        window.exec_()

    def on_create_identity_button_clicked(self):
        """
        Triggered when user click on create_identity_button

        :return:
        """
        window = IdentityCreateWindow(self.application, self.account)
        window.exec_()

    def on_certify_identity_button_clicked(self):
        """
        Triggered when user click on certify_identity_button

        :return:
        """
        if self.identity is not None:
            window = IdentityCertifyWindow(self.application, self.account)
            window.exec_()

    def on_identity_change_account_button_clicked(self):
        """
        Triggered when user click on identity change account button

        :return:
        """
        if self.identity is not None:
            window = IdentityChangeAccountWindow(self.application, self.account)
            window.exec_()


if __name__ == "__main__":
    qapp = QApplication(sys.argv)

    application_ = Application(TEST_DATA_PATH)

    account_ = application_.accounts.create_new_root_account(
        mnemonic="bottom drive obey lake curtain smoke basket hold race lonely fit walk",
        language_code="en",
        crypto_type=AccountCryptoType.ED25519,
        name="Root ED",
        password="aaaaaa",
    )

    identity_ = application_.identities.create(1, 0, 0, account_.address)
    application_.identities.add(identity_)

    # Create a certification where main account is issuer
    certification1 = Certification(
        id="test_certification_1_2",
        issuer_identity_index=1,
        issuer_identity_name="Alice",
        issuer_identity_status=IdentityStatus.MEMBER,
        issuer_address=account_.address,  # Main account is issuer
        receiver_identity_index=2,
        receiver_identity_name="Bob",
        receiver_identity_status=IdentityStatus.MEMBER,
        receiver_address="contact_address_123",
        created_on=datetime.now(),
        updated_on=datetime.now(),
        expire_on=datetime.now(),
    )
    certification2 = Certification(
        id="test_certification_2_1",
        issuer_identity_index=2,
        issuer_identity_name="Bob",
        issuer_identity_status=IdentityStatus.MEMBER,
        issuer_address="contact_address_123",  # Main account is issuer
        receiver_identity_index=1,
        receiver_identity_name="Alice",
        receiver_identity_status=IdentityStatus.MEMBER,
        receiver_address=account_.address,
        created_on=datetime.now(),
        updated_on=datetime.now(),
        expire_on=datetime.now(),
    )
    certification_datetime = datetime.now()
    # Create a certification where main account is issuer
    certification3 = Certification(
        id="test_certification_1_3",
        issuer_identity_index=1,
        issuer_identity_name="Alice",
        issuer_identity_status=IdentityStatus.MEMBER,
        issuer_address=account_.address,  # Main account is issuer
        receiver_identity_index=3,
        receiver_identity_name="Charlie",
        receiver_identity_status=IdentityStatus.MEMBER,
        receiver_address="contact_address_123",
        created_on=certification_datetime,
        updated_on=certification_datetime,
        expire_on=datetime.now(),
    )
    certification4 = Certification(
        id="test_certification_3_1",
        issuer_identity_index=3,
        issuer_identity_name="Charlie",
        issuer_identity_status=IdentityStatus.MEMBER,
        issuer_address="contact_address_123",  # Main account is issuer
        receiver_identity_index=1,
        receiver_identity_name="Alice",
        receiver_identity_status=IdentityStatus.MEMBER,
        receiver_address=account_.address,
        created_on=certification_datetime,
        updated_on=certification_datetime,
        expire_on=datetime.now(),
    )
    application_.certifications.set_list(
        identity_.index,
        [certification1, certification2, certification3, certification4],
    )

    main_window = QMainWindow()
    main_window.show()

    main_window.setCentralWidget(
        AccountIdentityWidget(application_, account_, main_window)
    )

    sys.exit(qapp.exec_())
