# 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.QtGui import QMovie
from PyQt5.QtWidgets import QApplication, QListWidgetItem, QMainWindow, QWidget

from tikka.domains.application import Application
from tikka.domains.entities.account import Account, AccountCryptoType
from tikka.domains.entities.constants import DATA_PATH
from tikka.domains.entities.technical_committee import (
    TechnicalCommitteeCall,
    TechnicalCommitteeMember,
    TechnicalCommitteeProposal,
    TechnicalCommitteeVoting,
)
from tikka.slots.pyqt.entities.constants import (
    ICON_LOADER,
)
from tikka.slots.pyqt.entities.event_bus import EventBus
from tikka.slots.pyqt.entities.worker import ThreadManager
from tikka.slots.pyqt.resources.gui.widgets.technical_committee_rc import (
    Ui_technicalCommitteeWidget,
)
from tikka.slots.pyqt.widgets.account_tabs.technical_committee_proposal import (
    AccountTechnicalCommitteeProposalWidget,
)


class AccountTechnicalCommitteeWidget(QWidget, Ui_technicalCommitteeWidget):
    """
    AccountTechnicalCommitteeWidget class
    """

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

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

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

        self.event_bus: EventBus = EventBus.instance()
        self.event_bus.repository_data_updated.connect(self.update_ui)

        self.account = account
        self.proposals_list_current_index = 0

        # animated loading icon
        self.loader_movie = QMovie(ICON_LOADER)
        self.loader_movie.start()
        self.loaderIconLabel.setMovie(self.loader_movie)
        loader_icon_size_policy = self.loaderIconLabel.sizePolicy()
        loader_icon_size_policy.setRetainSizeWhenHidden(True)
        self.loaderIconLabel.setSizePolicy(loader_icon_size_policy)
        self.loaderIconLabel.hide()

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

        self.update_ui()

    def init_proposal_list(self) -> None:
        """
        Init list of proposals

        :return:
        """

        scrollbar = self.proposalsListWidget.verticalScrollBar()
        if scrollbar.maximum() > 0:
            scroll_ratio = scrollbar.value() / scrollbar.maximum()
        else:
            scroll_ratio = 0
        current_row = self.proposalsListWidget.currentRow()

        self.proposalsListWidget.clear()

        for proposal in sorted(
            self.application.technical_committee.list_proposals(),
            key=lambda proposal: proposal.voting.index,
        ):
            item = QListWidgetItem(self.proposalsListWidget)
            self.proposalsListWidget.addItem(item)
            widget = AccountTechnicalCommitteeProposalWidget(
                self.application, self.account, proposal, parent=self
            )
            item.setSizeHint(widget.minimumSizeHint())

            # connect slot self.update_proposals to proposal item event
            widget.vote_for_proposal_start.connect(self.on_vote_for_proposal_start)
            widget.vote_for_proposal_done.connect(self.update_proposals)

            # Associate the custom widget to the list entry
            self.proposalsListWidget.setItemWidget(item, widget)

        if scrollbar.maximum() > 0:
            new_value = int(scroll_ratio * scrollbar.maximum())
            scrollbar.setValue(new_value)

        if 0 <= current_row < self.proposalsListWidget.count():
            self.proposalsListWidget.setCurrentRow(current_row)

    def fetch_proposals_from_network(self):
        """
        Fetch proposals of technical committee from network

        :return:
        """
        try:
            self.application.technical_committee.network_update_proposals()
        except Exception as exception:
            self.errorLabel.setText(self._(str(exception)))
            logging.exception(exception)

    def on_fetch_proposals_from_network_finished(self):
        """
        Triggered when async worker is finished

        :return:
        """
        logging.debug("Technical committee widget proposals update")
        self.init_proposal_list()
        self.loader_movie.stop()
        self.loaderIconLabel.hide()

    def async_refresh_data_from_network(self):
        """
        Refresh members and proposals from network

        :return:
        """
        self.thread_manager.start(
            self.fetch_proposals_from_network,
            self.on_fetch_proposals_from_network_finished,
        )

    def on_vote_for_proposal_start(self):
        """
        Vote request send, display loader waiting for vote done

        :return:
        """
        self.loader_movie.start()
        self.loaderIconLabel.show()
        self.proposals_list_current_index = (
            self.proposalsListWidget.currentIndex().row()
        )

    def update_proposals(self, error_message: str):
        """
        After a vote, update proposals list with new votes

        :param error_message: Error message, may be empty
        :return:
        """
        if error_message != "":
            self.errorLabel.setText(self._(error_message))

        self.thread_manager.start(
            self.fetch_proposals_from_network,
            self.on_fetch_proposals_from_network_finished,
        )

    def update_ui(self):
        """
        Update UI from repository data

        :return:
        """
        self.membersGroupBox.hide()
        self.refreshButton.hide()
        self.init_proposal_list()


if __name__ == "__main__":
    logging.basicConfig(level=logging.DEBUG)
    qapp = QApplication(sys.argv)

    application_ = Application(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",
    )

    technical_committee_member = TechnicalCommitteeMember(
        address=account_.address, identity_index=1, identity_name="root_ed"
    )
    application_.technical_committee.set_members_list([technical_committee_member])

    application_.technical_committee.set_proposals_list(
        [
            TechnicalCommitteeProposal(
                "proposal_hash",
                TechnicalCommitteeCall(
                    index=1,
                    hash="call_hash",
                    module="module",
                    function="function",
                    args="args",
                ),
                TechnicalCommitteeVoting(
                    index=1,
                    threshold=2,
                    ayes=["address1", "address2"],
                    nays=["address1", "address2", "address3"],
                    end=datetime.now(),
                ),
            )
        ]
    )

    main_window = QMainWindow()
    main_window.show()

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

    sys.exit(qapp.exec_())
