package dk.au.cs.snowfox;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.Background;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.stage.Stage;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.Buffer;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class Snowfox extends Application {

    private static String HOME = "http://cs.au.dk/";
    private String page = null;
    private LinkedList<String> history = new LinkedList<>();
    private int index = -1;

    @Override
    public void start(Stage primaryStage) throws IOException {

        VBox mainBox = new VBox();


        VBox pageView = new VBox();
        pageView.setMinHeight(200);
        pageView.setMinWidth(550);

        Label statusLine = new Label("Status: Ready");


        HBox navigationBox = new HBox();

        TextField urlField = new TextField();
        urlField.setText("https://cs.au.dk/~magnusm/");

        Button homeButton = new Button("Home");
        homeButton.setOnMouseClicked((MouseEvent e) -> {
            page = HOME;
            urlField.setText(HOME);
            history.add(HOME);
        });

        Button refreshButton = new Button("Refresh");
        Button backButton = new Button("<--");
        Button forwardButton = new Button("-->");

        backButton.setOnMouseClicked(e -> {
            index = index - 1;
            String url = history.get(index);
            urlField.setText(url);
            goUrl(url, pageView, statusLine);
            if (index == 0) {
                backButton.setDisable(true);
            }
            forwardButton.setDisable(false);
        });
        backButton.setDisable(true);

        forwardButton.setOnMouseClicked(e -> {
            index = index + 1;
            String url = history.get(index);
            urlField.setText(url);
            goUrl(url, pageView, statusLine);
            forwardButton.setDisable(index + 1 >= history.size());
        });
        forwardButton.setDisable(true);

        Button goButton = new Button("Go");
        goButton.setOnMouseClicked(e -> {
            String url = urlField.getText();
            history.add(url);
            goUrl(url, pageView, statusLine);
            index = index + 1;
            backButton.setDisable(!(index > 0));
        });

        Button darkMode = new Button("DarkMode");
        darkMode.setOnMouseClicked(e -> {
            pageView.setBackground(Background.fill(Color.BLACK));
        });

        navigationBox.getChildren().add(homeButton);
        navigationBox.getChildren().add(refreshButton);
        navigationBox.getChildren().add(backButton);
        navigationBox.getChildren().add(forwardButton);
        navigationBox.getChildren().add(urlField);
        navigationBox.getChildren().add(goButton);
        navigationBox.getChildren().add(darkMode);



        mainBox.getChildren().add(navigationBox);

        ScrollPane scrollViewPage = new ScrollPane(pageView);
        mainBox.getChildren().add(scrollViewPage);
        mainBox.getChildren().add(statusLine);

        Scene scene = new Scene(mainBox, 600, 400);
        primaryStage.setTitle("Snowfox");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    private void goUrl(String url, VBox pageView, Label statusLine) {
        // TODO: proper URL input validation
        // TODO: proper closing of input stream resources
        statusLine.setText("Navigating to: " + url);
        pageView.getChildren().clear();
        try {
            URL u = new URL(url);
            InputStream is = u.openStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));

            String line = null;
            String text = "";
            while ((line = reader.readLine()) != null) {
                String s = parseLine(line, pageView, statusLine);
                if (s != null) {
                    Label lineLabel = new Label(s);
                    pageView.getChildren().add(lineLabel);
                }
            }
        } catch (MalformedURLException e) {
            statusLine.setText("INVALID URL");
            statusLine.setBackground(Background.fill(Color.RED));
        } catch (IOException e) {
            statusLine.setText("CONNECTION BROKEN");
            statusLine.setBackground(Background.fill(Color.RED));        }

        statusLine.setText("Page loaded: " + url);
    }

    private String parseLine(String s, VBox pageView, Label statusLine) {
        // TODO: Try to parse b tag or h1
        LineParser p = new LineParser(s);
        p.setaTagHandler( (url, text) -> {
            Hyperlink link = new Hyperlink(text);
            link.setOnMouseClicked(e -> {

                goUrl(url, pageView, statusLine);
            });
            pageView.getChildren().add(link);

        });
        p.setH1TagHandler(text -> {
            Label label = new Label(text);
            label.setFont(Font.font(24));
            pageView.getChildren().add(label);
        });


        if (p.parse()) {
            return null;
        }
        return s;
    }
}
