package cz.jzitnik.events.handlers;

import com.googlecode.lanterna.SGR;
import com.googlecode.lanterna.TerminalSize;
import com.googlecode.lanterna.TextCharacter;
import com.googlecode.lanterna.TextColor;
import com.googlecode.lanterna.screen.Screen;
import com.googlecode.lanterna.screen.TerminalScreen;
import cz.jzitnik.annotations.EventHandler;
import cz.jzitnik.annotations.injectors.InjectState;
import cz.jzitnik.events.TerminalTooSmallEvent;
import cz.jzitnik.states.TerminalState;
import cz.jzitnik.utils.DependencyManager;
import cz.jzitnik.utils.events.AbstractEventHandler;

import java.io.IOException;

@EventHandler(TerminalTooSmallEvent.class)
public class TerminalTooSmallEventHandler extends AbstractEventHandler<TerminalTooSmallEvent> {
    public TerminalTooSmallEventHandler(DependencyManager dm) {
        super(dm);
    }

    @InjectState
    private TerminalState terminalState;

    @Override
    public void handle(TerminalTooSmallEvent event) {
        // Directly render message for the user
        TerminalScreen terminalScreen = terminalState.getTerminalScreen();
        terminalScreen.clear();

        TerminalSize terminalSize = terminalScreen.getTerminalSize();
        String text = "Terminal too small!";
        String subText = "Please resize your terminal";

        int startY = terminalSize.getRows() / 2;

        int textStartX = (terminalSize.getColumns() / 2) - (text.length() / 2);
        for (char character : text.toCharArray()) {
            terminalScreen.setCharacter(textStartX++, startY, new TextCharacter(character, TextColor.ANSI.RED, TextColor.ANSI.DEFAULT, SGR.BOLD));
        }
        int subTextStartX = (terminalSize.getColumns() / 2) - (subText.length() / 2);
        for (char character : subText.toCharArray()) {
            terminalScreen.setCharacter(subTextStartX++, startY + 1, new TextCharacter(character, TextColor.ANSI.BLACK_BRIGHT, TextColor.ANSI.DEFAULT));
        }

        try {
            terminalScreen.refresh(Screen.RefreshType.COMPLETE);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
