# 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/>.

from gi.repository import Gtk

from saldo.backend.account_data import AccountData
from saldo.backend.helper import money
from saldo.widgets.transaction_row import TransactionRow


@Gtk.Template(resource_path="/org/tabos/saldo/ui/account_row.ui")
class AccountRow(Gtk.ListBoxRow):
    __gtype_name__ = "AccountRow"

    _image = Gtk.Template.Child()
    _product_label = Gtk.Template.Child()
    _account_label = Gtk.Template.Child()
    _owner_label = Gtk.Template.Child()
    _balance_label = Gtk.Template.Child()

    def __init__(self, account, backend):
        super().__init__()

        self.transactions = []
        self._backend = backend
        self.set_info(account)

    def set_info(self, account):
        self._account = account

        # Set image
        self._image.set_icon_size(Gtk.IconSize.LARGE)
        self._image.set_from_icon_name(self._account.logo)

        # Set text
        self._product_label.set_markup(f"<b>{self._account.product_name}</b>")
        self._account_label.set_text(self._account.iban)
        self._owner_label.set_markup(f"<small>{self._account.owner_name}</small>")

        # Set balance
        balance = money(self._account.balance)
        self._balance_label.set_text(f"{balance} {self._account.currency}")

        if self._account.balance < 0.0:
            self._balance_label.add_css_class("error")
        else:
            self._balance_label.add_css_class("success")

        self.transactions = []
        for transaction in account.transactions:
            trow = TransactionRow(transaction, self._backend)
            self.transactions.append(trow)

    @property
    def account(self):
        return self._account

    @account.setter
    def account(self, account: AccountData) -> None:
        self.set_info(account)
