package xyz.thastertyn.UserInterface;

import java.io.IOException;
import java.util.Arrays;

import com.googlecode.lanterna.TextColor;
import com.googlecode.lanterna.gui2.BasicWindow;
import com.googlecode.lanterna.gui2.Borders;
import com.googlecode.lanterna.gui2.DefaultWindowManager;
import com.googlecode.lanterna.gui2.Direction;
import com.googlecode.lanterna.gui2.EmptySpace;
import com.googlecode.lanterna.gui2.LinearLayout;
import com.googlecode.lanterna.gui2.MultiWindowTextGUI;
import com.googlecode.lanterna.gui2.Panel;
import com.googlecode.lanterna.gui2.Window;
import com.googlecode.lanterna.screen.Screen;
import com.googlecode.lanterna.screen.TerminalScreen;
import com.googlecode.lanterna.terminal.DefaultTerminalFactory;
import com.googlecode.lanterna.terminal.Terminal;

import xyz.thastertyn.Login.LoginController;
import xyz.thastertyn.UserInterface.Listeners.WindowSwitchListener;

public class MainWindow {

	private Terminal terminal;
	private Screen screen;
	private Window window;
	private MultiWindowTextGUI textGUI;

	/**
	 * Create: 
	 * <ul>
	 * <li> All the main components like Terminal, and Screen </li>
	 * <li> {@link LoginController} and try logging in using any of its methods </li>
	 * <li> {@link WindowSwitchListener} for the purpose of switching between tabs using {@code Tab} and {@code ReverseTab} (Shift + Tab) </li>
	 * </ul> 
	 */
	public void run()
	{
		try {
			//#region init
			// Setup terminal and screen layers
			terminal = new DefaultTerminalFactory().createTerminal();

			screen = new TerminalScreen(terminal);
			screen.startScreen();

			// Create window to hold the panel
			window = new BasicWindow();
			window.setHints(Arrays.asList(Window.Hint.CENTERED));

			// Create gui and start gui
			textGUI = new MultiWindowTextGUI(screen, new DefaultWindowManager(), new EmptySpace(TextColor.ANSI.BLACK_BRIGHT));
			//#endregion

			// Create panel to hold all components
			final Panel mainPanel = new Panel(new LinearLayout(Direction.VERTICAL));
			
			window.setComponent(mainPanel);

			// Create a secondary panel, as working with the mainPanel is quite buggy
			Panel content = new Panel();
			mainPanel.addComponent(content.withBorder(Borders.singleLine("Jecnak")));

			// Try logging in using any method
			LoginController controller = new LoginController(textGUI);
			controller.login(false);

			// Create a WindowListener for tab and shift tab for moving between tabs
			window.addWindowListener(new WindowSwitchListener(content, textGUI));

			textGUI.addWindowAndWait(window);

		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
