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

from PyQt5.QtWidgets import QApplication, QMenu, QWidget

from tikka.domains.application import Application
from tikka.domains.entities.account import Account
from tikka.domains.entities.constants import DATA_PATH
from tikka.domains.entities.identity import Certification, IdentityStatus
from tikka.slots.pyqt.windows.identity_certify import IdentityCertifyWindow
from tikka.slots.pyqt.windows.transfer import TransferWindow


class AccountCertificationsPopupMenu(QMenu):
    """
    AccountCertificationsPopupMenu class
    """

    def __init__(
        self,
        application: Application,
        account: Account,
        certification: Certification,
        parent: Optional[QWidget] = None,
    ):
        """
        Init TransferHistoryPopupMenu instance

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

        self.application = application
        self.account = account
        self.certification = certification
        self._ = self.application.translator.gettext

        self.contact_address = (
            self.certification.issuer_address
            if self.certification.issuer_address != self.account.address
            else self.certification.receiver_address
        )
        self.contact_identity_name = (
            self.certification.issuer_identity_name
            if self.certification.issuer_address != self.account.address
            else self.certification.receiver_identity_name
        )
        self.contact_identity_index = (
            self.certification.issuer_identity_index
            if self.certification.issuer_address != self.account.address
            else self.certification.receiver_identity_index
        )

        # Create all menu actions and disable them based on conditions
        transfer_to_action = self.addAction(self._("Transfer to"))
        transfer_to_action.triggered.connect(self.transfer_to)

        transfer_from_action = self.addAction(self._("Transfer from"))
        transfer_from_action.triggered.connect(self.transfer_from)

        certify_action = self.addAction(self._("Certify"))
        certify_action.triggered.connect(self.certify)

        # Enable/disable actions based on conditions
        if not self.application.wallets.exists(self.account.address):
            transfer_to_action.setEnabled(False)
            certify_action.setEnabled(False)
        else:
            # Check if identity exists for certification
            if self.application.identities.get(self.contact_identity_index) is None:
                certify_action.setEnabled(False)

        if not self.application.wallets.exists(self.contact_address):
            transfer_from_action.setEnabled(False)

        # Separator
        self.addSeparator()

        # menu actions
        copy_address_to_clipboard_action = self.addAction(
            self._("Copy address to clipboard")
        )
        copy_address_to_clipboard_action.triggered.connect(
            self.copy_address_to_clipboard
        )

        self.contact_account = self.application.accounts.get_by_address(
            self.contact_address
        )

        add_account_address_action = self.addAction(self._("Add address to accounts"))
        add_account_address_action.triggered.connect(self.add_address_to_accounts)

        # Disable "Add address to accounts" if account already exists
        if self.contact_account is not None:
            add_account_address_action.setEnabled(False)

    def copy_address_to_clipboard(self):
        """
        Copy address of selected row to clipboard

        :return:
        """
        clipboard = QApplication.clipboard()
        clipboard.setText(self.contact_address)

    def transfer_to(self):
        """
        Open transfer window with account as recipient

        :return:
        """
        if self.contact_account is None:
            self.contact_account = Account(
                self.contact_address,
                f"{self.contact_identity_name}#{self.contact_identity_index}",
            )

        TransferWindow(
            self.application,
            self.account,
            self.contact_account,
            parent=self,
        ).exec_()

    def transfer_from(self):
        """
        Open transfer window with account as sender

        :return:
        """
        TransferWindow(
            self.application,
            self.contact_account,
            self.account,
            parent=self,
        ).exec_()

    def add_address_to_accounts(self):
        """
        Add a new account from contact address

        :return:
        """
        self.contact_account = Account(self.contact_address)

        self.application.accounts.add(self.contact_account)

    def certify(self):
        """
        Open certify window with account as issuer and contact_account as receiver

        :return:
        """
        self.contact_account = Account(self.contact_address)
        IdentityCertifyWindow(
            self.application,
            self.account,
            self.contact_account,
            parent=self,
        ).exec_()


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

    application_ = Application(DATA_PATH)
    account_ = Account("732SSfuwjB7jkt9th1zerGhphs6nknaCBCTozxUcPWPU")
    certification_ = Certification(
        id="test_certification_1_2",
        issuer_identity_index=1,
        issuer_identity_name="Alice",
        issuer_identity_status=IdentityStatus.MEMBER,
        issuer_address="xxxxx",
        receiver_identity_index=2,
        receiver_identity_name="Bob",
        receiver_identity_status=IdentityStatus.MEMBER,
        receiver_address="yyyy",
        created_on=datetime.datetime.now(),
        updated_on=datetime.datetime.now(),
        expire_on=datetime.datetime.now(),
    )
    menu = AccountCertificationsPopupMenu(application_, account_, certification_)
    menu.exec_()

    sys.exit(qapp.exec_())
