package com.example;

import java.io.BufferedReader;
import java.io.IOException;

import com.example.Controllers.Controller;
import com.example.Exceptions.BaseException;
import com.example.Models.Program.GenericDictionary;
import com.example.Models.Program.GenericQueue;
import com.example.Models.Program.GenericStack;
import com.example.Models.Program.Heap;
import com.example.Models.Program.ProgramState;
import com.example.Models.Program.SemaphoreTable;
import com.example.Models.Statements.IStatement;
import com.example.Models.Values.IValue;
import com.example.Models.Values.StringValue;
import com.example.Repositories.IRepository;
import com.example.Repositories.Repository;

import javafx.collections.FXCollections;
import javafx.fxml.FXML;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonType;
import javafx.scene.control.ListView;
import javafx.scene.layout.Region;

public class ListController {

    private ProgramController programController;

    public void setProgramController(ProgramController programController) {
        this.programController = programController;
    }

    @FXML
    private ListView<IStatement> statements;

    @FXML
    private Button displayButton;

    @FXML
    public void initialize() {
        statements.setItems(FXCollections.observableArrayList(Examples.exampleList()));
        displayButton.setOnAction(actionEvent -> {
            int index = statements.getSelectionModel().getSelectedIndex();
            if (index < 0)
                return;
            try{
                ProgramState state = new ProgramState(new GenericStack<IStatement>(), new GenericDictionary<String, IValue>(), new GenericQueue<IValue>(), new GenericDictionary<StringValue, BufferedReader>(), new Heap(), new SemaphoreTable(), Examples.exampleList()[index]);
                IRepository repository = new Repository("log.txt");
                repository.addProgramState(state);
                Controller controller = new Controller(repository, true);
                programController.setController(controller);
            } catch (BaseException interpreterError) {
                Alert alert = new Alert(Alert.AlertType.ERROR, interpreterError.getMessage(), ButtonType.OK);
                alert.getDialogPane().setMinHeight(Region.USE_PREF_SIZE);
                alert.showAndWait();
            }
        });
    }
}
