# 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 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, SearchAccount
from tikka.domains.entities.constants import TEST_DATA_PATH
from tikka.slots.pyqt.entities.event_bus import EventBus
from tikka.slots.pyqt.windows.transfer import TransferWindow


class AccountSearchPopupMenu(QMenu):
    """
    AccountSearchPopupMenu class
    """

    def __init__(
        self,
        application: Application,
        search_account: SearchAccount,
        parent: Optional[QWidget] = None,
    ):
        """
        Init TransferHistoryPopupMenu instance

        :param application: Application instance
        :param search_account: SearchAccount instance
        :param parent: QWidget instance
        """
        super().__init__(parent=parent)

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

        self.event_bus: EventBus = EventBus.instance()

        # Transfer actions
        transfer_to_action = self.addAction(self._("Transfer to"))
        transfer_to_action.triggered.connect(self.transfer_to)

        # Enable/disable transfer actions based on conditions
        if not self.application.connections.node.is_connected():
            transfer_to_action.setEnabled(False)

        # Separator
        self.addSeparator()

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

        # Get contact account
        self.contact_account = self.application.accounts.get_by_address(
            self.search_account.address
        )

        # Add address to accounts action
        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.search_account.address)

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

        :return:
        """
        if self.contact_account is None:
            self.contact_account = Account(
                self.search_account.address,
                f"{self.search_account.identity_name}#{self.search_account.identity_index}"
                if self.search_account.identity_index is not None
                else None,
            )

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

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

        :return:
        """
        self.contact_account = Account(self.search_account.address)

        self.application.accounts.add(self.contact_account)
        self.event_bus.account_added.emit(self.contact_account)


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

    application_ = Application(TEST_DATA_PATH)
    search_account_ = SearchAccount("732SSfuwjB7jkt9th1zerGhphs6nknaCBCTozxUcPWPU", 0)
    menu = AccountSearchPopupMenu(application_, search_account_)
    menu.exec_()

    sys.exit(qapp.exec_())
