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();
    }

    /**
     * Sets the profile and BMS used to manage banking.
     * @param profile the profile used to manage the account
     * @param bms the BMS used access other banking accounts
     */
    public void setProfile(Profile profile, BankingManagementSystem bms) {
        this.profile = profile;
        this.view.setProfile(profile);
        this.data.setBms(bms);
        this.createListeners();
    }

    /**
     * Create listeners for GUI components
     */
    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());
    }

    /**
     * Open dialog to deposit money
     */
    private void depositMoney() {
        new DepositController(profile.getPrimaryAccount());
        this.view.updateAccountVariables(profile);
    }

    /**
     * Open dialog to transfer money
     */
    private void transferMoney() {
        new TransferController(profile.getPrimaryAccount(), data.getBms());
        this.view.updateAccountVariables(profile);
    }

    /**
     * Open dialog to take off money
     */
    private void takeoffMoney() {
        new TakeoffController(profile.getPrimaryAccount());
        this.view.updateAccountVariables(profile);
    }

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

    /**
     * Change the selected account.
     */
    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;
    }
}
