# Copyright (c) 2020-2022 Jan-Michael Brummer <jan.brummer@tabos.org>
#
# This program 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 program 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/>.

"""
Transaction row, showing transaction information
"""

from gi.repository import Adw, Gtk

from saldo.backend.backend import BankingBackend
from saldo.backend.helper import money
from saldo.backend.transaction_data import TransactionData


class TransactionRow(Adw.ActionRow):
    _applicant_name_label = Gtk.Template.Child()
    _sub_label = Gtk.Template.Child()
    _amount_label = Gtk.Template.Child()

    def __init__(self, transaction_data: TransactionData, backend: BankingBackend):
        super().__init__()

        self._backend = backend
        self.avatar = None
        self.set_info(transaction_data)

    def set_info(self, transaction_data):
        self._transaction = transaction_data
        self.set_activatable(True)
        self.set_property("title-lines", 1)
        self.set_property("subtitle-lines", 1)

        name = self._transaction.name
        self.set_title(name)
        self.set_subtitle(self._backend.category_get_name(name))

        self.avatar = Adw.Avatar()
        self.avatar.set_size(32)
        self._backend.category_set_avatar(self.avatar, name)
        self.add_prefix(self.avatar)
        self.add_css_class("card")
        self.set_margin_top(6)
        self.set_margin_bottom(6)

        amount = money(self._transaction.amount)
        amount_label = Gtk.Label()
        amount_label.set_text(amount + " " + self._transaction.currency)

        self.add_suffix(amount_label)
        if self._transaction.amount >= 0.0:
            amount_label.add_css_class("success")
        else:
            amount_label.add_css_class("error")

    @property
    def transaction(self) -> TransactionData:
        return self._transaction

    @transaction.setter
    def transaction(self, transaction: TransactionData) -> None:
        self.set_info(transaction)

    def update_category(self):
        name = self._transaction.name
        self._backend.category_set_avatar(self.avatar, name)
        self.set_subtitle(self._backend.category_get_name(name))
