package id.co.gtc.erhacam;

import Database.TinyLogRow;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import lombok.val;
import org.tinylog.Logger;

import java.io.IOException;
import java.nio.file.Files;
import java.util.concurrent.atomic.AtomicInteger;

import static Config.SomeCodes.GetLogsPath;

public class LogsView {

    @FXML
    private ComboBox<String> datePicker;

    @FXML
    private TextField searchField;

    @FXML
    private TableView<TinyLogRow> logTable;

    @FXML
    private Button PopulateButton;

    private ObservableList<TinyLogRow> tablerows ;

    @FXML
    private void initialize(){
        tablerows = FXCollections.observableArrayList();
        logTable.setItems(tablerows);
        initialize_tableview();


        datePicker.onActionProperty().set(e->{
            String selected = datePicker.getValue();
            tablerows.clear();
            try {
                AtomicInteger index = new AtomicInteger(1);
                Files.lines(GetLogsPath().resolve(selected+".log"))
                        .forEachOrdered(l->{
                            TinyLogRow row = TinyLogRow.Regex(l);
                            if (row != null  && row.HaveContent()) {
                                row.setIndex(index.getAndIncrement());
                                tablerows.add(row);
                            }
                        });
            } catch (IOException ex) {
                Logger.error("datePicker error: {}", ex.getMessage());
            }



        });

        PopulateButton.onActionProperty().set(e->{
            datePicker.getItems().clear();
            try {
                Files.list(GetLogsPath())
                        .filter(p -> p.toFile().isFile())
                        .filter(p -> p.getFileName().toString().endsWith(".log"))
                        .forEachOrdered(p->{
                            String ss = p.getFileName().toString();
                            datePicker.getItems().add(ss.substring(0, ss.lastIndexOf('.')));
                        });

            } catch (IOException ex) {
                Logger.error("PopulateButton error: {}", ex.getMessage());
            }

        });

        searchField.onKeyTypedProperty().set(e->{
            String search = searchField.getText().toLowerCase();
            if (search.length() > 0){
                ObservableList<TinyLogRow> filtered = FXCollections.observableArrayList();
                tablerows.forEach(r->{
                    if (r.getMessage().toLowerCase().contains(search)){
                        filtered.add(r);
                    }
                });
                logTable.setItems(filtered);
            } else {
                logTable.setItems(tablerows);
            }
        });

        Platform.runLater(()->{
            PopulateButton.fire();  // trigger PopulateButton on show
        });
    }

    private void initialize_tableview(){
        logTable.getColumns().clear();

        TableColumn<TinyLogRow,Integer> indexCol = new TableColumn<>("No");
        indexCol.setCellValueFactory(new PropertyValueFactory<>("index"));

        TableColumn<TinyLogRow,String> datetimeCol = new TableColumn<>("DateTime");
        datetimeCol.setCellValueFactory(new PropertyValueFactory<>("DateTime"));

        TableColumn<TinyLogRow,String> categoryCol = new TableColumn<>("Category");
        categoryCol.setCellValueFactory(new PropertyValueFactory<>("Category"));

        TableColumn<TinyLogRow,String> messageCol = new TableColumn<>("Message");
        messageCol.setCellValueFactory(new PropertyValueFactory<>("Message"));


        logTable.getColumns().add(indexCol);
        logTable.getColumns().add(datetimeCol);
        logTable.getColumns().add(categoryCol);
        logTable.getColumns().add(messageCol);

        logTable.widthProperty().addListener((obs, oldVal, newVal)->{
            double width = (double)newVal;
            if (width > (75+150+75+100)){
                // cukup besar, pake patokan
                indexCol.setPrefWidth(75);
                datetimeCol.setPrefWidth(150);
                categoryCol.setPrefWidth(75);
                messageCol.setPrefWidth(width-300);
            } else {
                // kecil, pake persen
                indexCol.setPrefWidth(width*0.075);
                datetimeCol.setPrefWidth(width*0.15);
                categoryCol.setPrefWidth(width*0.075);
                messageCol.setPrefWidth(width*0.7);
            }

        });
    }

    public void Unload(){

    }
}
