import React, { ChangeEvent } from "react";
import { saveGraphJson } from "../../../datasets";
import ManagedData from "../structures/manageddata";
import "./historynavigator.css";

type propTypes = {
    historyObject: ManagedData;
    spaceId: string;
    onChange: { (): void };
};

export class HistoryNavigator extends React.Component<propTypes> {
    constructor(props: propTypes) {
        super(props);

        this.handleUndo = this.handleUndo.bind(this);
        this.handleRedo = this.handleRedo.bind(this);
        this.handleSave = this.handleSave.bind(this);
        this.handleSelectSavepoint = this.handleSelectSavepoint.bind(this);
    }

    /**
     * Undo a step in the history object.
     */
    handleUndo() {
        this.props.historyObject.undo();
    }

    /**
     * Redo a step in the hisory object.
     */
    handleRedo() {
        this.props.historyObject.redo();
    }

    /**
     * Saves current data of history object.
     */
    handleSave() {
        saveGraphJson(this.props.spaceId, this.props.historyObject.serialize());
        // TODO: Save successful?
        this.props.historyObject.markChangesAsSaved();
        alert(
            "Saved! (Though not for sure, currently not checking for success of failure)"
        );
    }

    /**
     * Loads selected savepoint into history object.
     */
    handleSelectSavepoint(e: ChangeEvent<HTMLSelectElement>) {
        if (!this.props.historyObject.goToSavePoint(Number(e.target.value))) {
            alert("Something went wrong, could not load savepoint.");
        } else {
            this.props.onChange();
        }
    }

    render(): React.ReactNode {
        return (
            <div id="history-navigator">
                <button onClick={this.handleUndo}>Undo</button>
                <button onClick={this.handleRedo}>Redo</button>
                <select
                    onChange={this.handleSelectSavepoint}
                    value={
                        this.props.historyObject
                            ? this.props.historyObject.currentSavePoint.id
                            : 0
                    }
                >
                    {this.props.historyObject
                        ? this.props.historyObject.history.map((savepoint) => {
                              return (
                                  <option
                                      key={savepoint.id}
                                      value={savepoint.id}
                                  >
                                      {savepoint.description}
                                  </option>
                              );
                          })
                        : ""}
                </select>
                <button onClick={this.handleSave}>Save</button>
            </div>
        );
    }
}