package me.teridax.jcash.gui.takeoff;

import me.teridax.jcash.Logging;
import me.teridax.jcash.banking.accounts.Account;
import me.teridax.jcash.banking.accounts.CurrentAccount;
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;

public class TakeoffController {

    private final Account account;
    private final TakeoffView view;
    private final TakeoffData data;

    public TakeoffController(Account account) {
        this.account = account;

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

        this.data = new TakeoffData(account.getBalance());
        this.view = new TakeoffView(this.data.getMaxValue() + overdraft);

        this.view.getTakeoff().addActionListener(e -> takeOff());
        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.getTakeoff().setEnabled(true);
                } catch (InvalidInputException | ParseException ex) {
                    view.setCommittedValue(0, balance);
                    view.getTakeoff().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 takeOff() {
        try {
            account.takeoff(view.getAmount());
        } catch (IllegalArgumentException | InvalidInputException ex) {
            Logging.LOGGER.severe("Could not take off money: " + ex.getMessage());
            Utils.error("Reason: " + ex.getMessage());
        }
        view.dispose();
    }
}
