package me.teridax.jcash.gui.transfer;

import me.teridax.jcash.Logging;
import me.teridax.jcash.Main;
import me.teridax.jcash.banking.accounts.Account;
import me.teridax.jcash.banking.accounts.CurrentAccount;
import me.teridax.jcash.banking.management.BankingManagementSystem;
import me.teridax.jcash.gui.InvalidInputException;
import me.teridax.jcash.gui.Utils;

import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import java.text.ParseException;

/**
 * Dialog class for transferring some value from one account to another
 */
public class TransferController {

    private final Account account;
    private final TransferData transferData;
    private final TransferView view;

    public TransferController(Account account, BankingManagementSystem bms) {
        this.account = account;

        var overdraft = 0.0;
        if (account instanceof CurrentAccount) {
            overdraft += ((CurrentAccount) account).getOverdraft();
        }

        this.view = new TransferView(account.getBalance() + overdraft);
        this.transferData = new TransferData(bms);
        this.view.getTransfer().addActionListener(e -> transfer());
        this.view.getCancel().addActionListener(e -> view.dispose());
        this.view.getValue().getDocument().addDocumentListener(new DocumentListener() {
            private void validateInputState() {
                var balance = account.getBalance();
                try {
                    view.getValue().commitEdit();
                    var amount = view.getAmount();
                    view.setCommittedValue(amount, balance - amount);
                    view.getTransfer().setEnabled(true);
                } catch (InvalidInputException | ParseException ex) {
                    view.setCommittedValue(0, balance);
                    view.getTransfer().setEnabled(false);
                }
            }

            @Override
            public void insertUpdate(DocumentEvent documentEvent) {
                validateInputState();
            }

            @Override
            public void removeUpdate(DocumentEvent documentEvent) {
                validateInputState();
            }

            @Override
            public void changedUpdate(DocumentEvent documentEvent) {
                validateInputState();
            }
        });
        this.view.showDialog();
    }

    private void transfer() {
        try {
            var amount = view.getAmount();
            this.account.takeoff(amount);
            this.transferData.transferValue(amount, view.getBlz(), view.getIban());
        } catch (IllegalArgumentException | InvalidInputException ex) {
            Logging.LOGGER.severe("Could not transfer: " + ex.getMessage());
            Utils.error("Reason: " + ex.getMessage());
        }
        this.view.dispose();
    }
}
