package me.teridax.jcash.gui.account;

import me.teridax.jcash.Logging;
import me.teridax.jcash.Main;
import me.teridax.jcash.banking.management.BankingManagementSystem;
import me.teridax.jcash.banking.management.Profile;
import me.teridax.jcash.gui.deposit.DepositController;
import me.teridax.jcash.gui.takeoff.TakeoffController;
import me.teridax.jcash.gui.transfer.TransferController;

/**
 * Controller for controlling the gui of an account.
 */
public class AccountController {
    private final AccountData data;
    /**
     * GUI if an account
     */
    private final AccountView view;

    private Profile profile;

    public AccountController() {
        this.view = new AccountView();
        this.data = new AccountData();
    }

    public void setProfile(Profile profile, BankingManagementSystem bms) {
        this.profile = profile;
        this.view.setProfile(profile);
        this.data.setBms(bms);
        this.createListeners();
    }

    private void createListeners() {
        this.view.getAccountSelection().addActionListener(e -> changeAccount());
        this.view.getLogout().addActionListener(e -> logout());
        this.view.getDeposit().addActionListener(e -> depositMoney());
        this.view.getTakeoff().addActionListener(e -> takeoffMoney());
        this.view.getTransfer().addActionListener(e -> transferMoney());
    }

    private void depositMoney() {
        new DepositController(profile.getPrimaryAccount());
        this.view.updateAccountVariables(profile);
    }

    private void transferMoney() {
        new TransferController(profile.getPrimaryAccount(), data.getBms());
        this.view.updateAccountVariables(profile);
    }

    private void takeoffMoney() {
        new TakeoffController(profile.getPrimaryAccount());
        this.view.updateAccountVariables(profile);
    }

    private void logout() {
        Logging.LOGGER.fine("Logging out of account");
        Main.getInstance().logout();
        Main.getInstance().showLoginScreen();
    }

    private void changeAccount() {
        var description = ((String) this.view.getAccountSelection().getSelectedItem());
        Logging.LOGGER.fine("Changing primary account selected: " + description);
        this.profile.setPrimaryAccount(description);
        this.view.setProfile(profile);
    }

    public AccountView getView() {
        return view;
    }
}
