package org.academiadecodigo.enuminatti.fx.calculator;

import javafx.event.EventHandler;
import javafx.scene.control.Button;
import javafx.scene.input.InputEvent;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseEvent;

public class Controller implements EventHandler<InputEvent> {
    private CalculatorUI ui;
    private CalculatorBrain brain;
    private boolean newNumber;

    private void handleButtonId(String buttonId) {
        if(brain.isDigit(buttonId)) {
            handleDigit(buttonId);

        } else {
            Operation parsedOption = Operation.getOperation(buttonId);

            String screenText = ui.getDisplayText();
            if (parsedOption == Operation.DELETE) {
                deleteLastDigit(screenText);
                return;
            }

            String result = brain.calculate(screenText, parsedOption, newNumber);
            newNumber = false;

            ui.setDisplayText(result);
            ui.setOperation(brain.getMathOperation());
        }
    }

    private void handleDigit(String buttonId) {
        Long.parseLong(buttonId);

        if (!newNumber) {
            ui.setDisplayText(buttonId);
            newNumber = true;
            return;
        }

        ui.appendDisplayText(buttonId);
        newNumber = true;
    }

    private void deleteLastDigit(String screenText) {
        if (screenText.length() <= 1) {
            ui.setDisplayText("0");
            return;
        }

        ui.setDisplayText(screenText.substring(0, screenText.length() - 1));

    }

    @Override
    public void handle(InputEvent event) {
        if (event instanceof MouseEvent) {
            MouseEvent mouseEvent = (MouseEvent) event;
            handleButtonId(((Button) mouseEvent.getSource()).getId());

        } else if (event instanceof KeyEvent) {
            KeyEvent keyEvent = (KeyEvent) event;
            String id = keyEvent.getText();

            switch (keyEvent.getCode()) {
                case ENTER:
                    id = "=";
                    break;
                case ESCAPE:
                    id = "C";
                    break;
                case BACK_SPACE:
                    id = "DEL";
                    break;
                default:
                    if (!id.matches("[\\dC=/*x:+-]")) {
                        return;
                    }
            }

            handleButtonId(id);
        }
    }

    public void setBrain(CalculatorBrain brain) {
        this.brain = brain;
    }

    public void setUi(CalculatorUI ui) {
        this.ui = ui;
    }
}
