package ctbrec.ui.action;

import static ctbrec.SubsequentAction.*;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.concurrent.CompletableFuture;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import ctbrec.GlobalThreadPool;
import ctbrec.Model;
import ctbrec.SubsequentAction;
import ctbrec.recorder.Recorder;
import ctbrec.ui.controls.Dialogs;
import javafx.geometry.Insets;
import javafx.scene.Cursor;
import javafx.scene.Node;
import javafx.scene.control.DatePicker;
import javafx.scene.control.Label;
import javafx.scene.control.RadioButton;
import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;

public class SetStopDateAction {

    private static final Logger LOG = LoggerFactory.getLogger(SetStopDateAction.class);

    private Node source;
    private Model model;
    private Recorder recorder;

    public SetStopDateAction(Node source, Model model, Recorder recorder) {
        this.source = source;
        this.model = model;
        this.recorder = recorder;
    }

    public CompletableFuture<Boolean> execute() {
        source.setCursor(Cursor.WAIT);
        DatePicker datePicker = new DatePicker();
        GridPane gridPane = new GridPane();
        gridPane.setHgap(10);
        gridPane.setVgap(10);
        gridPane.setPadding(new Insets(20, 150, 10, 10));
        gridPane.add(new Label("Stop at"), 0, 0);
        gridPane.add(datePicker, 1, 0);
        gridPane.add(new Label("And then"), 0, 1);
        ToggleGroup toggleGroup = new ToggleGroup();
        RadioButton pauseButton = new RadioButton("pause recording");
        pauseButton.setSelected(model.getRecordUntilSubsequentAction() == PAUSE);
        pauseButton.setToggleGroup(toggleGroup);
        RadioButton removeButton = new RadioButton("remove model");
        removeButton.setSelected(model.getRecordUntilSubsequentAction() == REMOVE);
        removeButton.setToggleGroup(toggleGroup);
        HBox row = new HBox();
        row.getChildren().addAll(pauseButton, removeButton);
        HBox.setMargin(pauseButton, new Insets(5));
        HBox.setMargin(removeButton, new Insets(5));
        gridPane.add(row, 1, 1);
        if (model.isRecordingTimeLimited()) {
            LocalDate localDate = LocalDate.ofInstant(model.getRecordUntil(), ZoneId.systemDefault());
            datePicker.setValue(localDate);
        }
        boolean userClickedOk = Dialogs.showCustomInput(source.getScene(), "Stop Recording at", gridPane);
        return CompletableFuture.supplyAsync(() -> {
            if (userClickedOk) {
                SubsequentAction action = pauseButton.isSelected() ? PAUSE : REMOVE;
                LOG.info("Stop at {} and {}", datePicker.getValue(), action);
                Instant stopAt = Instant.from(datePicker.getValue().atStartOfDay().atZone(ZoneId.systemDefault()));
                model.setRecordUntil(stopAt);
                model.setRecordUntilSubsequentAction(action);
                try {
                    recorder.stopRecordingAt(model);
                } catch (InvalidKeyException | NoSuchAlgorithmException | IOException e) {
                    Dialogs.showError(source.getScene(), "Error", "Couln't set stop date", e);
                }
            }
            return true;
        }, GlobalThreadPool.get()).whenComplete((r, e) -> {
            source.setCursor(Cursor.DEFAULT);
            if (e != null) {
                LOG.error("Error", e);
            }
        });
    }



}
