package me.teridax.jcash.banking.management;

import me.teridax.jcash.Logging;
import me.teridax.jcash.banking.Bank;
import me.teridax.jcash.banking.accounts.Account;
import me.teridax.jcash.banking.accounts.Owner;

import java.util.Arrays;

/**
 * Groups an owner and all of its accounts registered at a specific bank together.
 * The profile is oriented around a primary account of the owner.
 * This class is meant to be a read only reference for easier runtime processing of
 * data packed into nested structure of objects.
 */
public class Profile {

    /**
     * Owner of the primary account and all other accounts registered at a specific bank
     */
    private final Owner owner;
    /**
     * The bank that manages every account referenced by this profile
     */
    private final Bank bank;
    /**
     * All other account registered at a specific bank for the specified owner
     */
    private final Account[] accounts;
    /**
     * Primary or currently selected account.
     */
    private Account primaryAccount;

    public Profile(Owner owner, Bank bank, Account account, Account[] accounts) {
        if (!Arrays.asList(accounts).contains(account)) {
            Logging.LOGGER.severe("Account not found:" + account.getDescription());
            throw new IllegalArgumentException("Primary account is not registered at the bank");
        }

        this.owner = owner;
        this.bank = bank;
        this.accounts = accounts;
        this.primaryAccount = account;
    }

    public Account getPrimaryAccount() {
        return primaryAccount;
    }

    /**
     * Set the primary account of this profile based on a descriptive text.
     * This method may not change anything if no account can be found with a matching description
     *
     * @param description the description to find a matching account for
     */
    public void setPrimaryAccount(String description) {
        for (Account account : accounts) {
            if (account.getDescription().equals(description)) {
                this.primaryAccount = account;
                break;
            }
        }
        Logging.LOGGER.warning("Account " + description + " not found in associated account list");
    }

    public Owner getOwner() {
        return owner;
    }

    public Bank getBank() {
        return bank;
    }

    public Account[] getAccounts() {
        return accounts;
    }
}
