import { createSignal } from "solid-js";
import Command from "../data/command.js";
import RemotesService from "../services/remotes-service.js";
import EventEmitter from "../tools/event-emitter.js";
import ModalHandler from "./modal-handler.js";
import Modal from "./modal.jsx";

const [command, setCommand] = createSignal(new Command());
const eventEmitter = new EventEmitter();
const COMMAND_DELETED_EVENT = "success";

function DeleteCommandModal(props) {
  const [error, setError] = createSignal("");

  async function handleDeleteCommand() {
    try {
      await RemotesService.deleteCommand(command().getId());
    } catch (e) {
      setError(e.message);
      throw e;
    }
    DeleteCommandModal.Handler.hide();
    eventEmitter.dispatchEvent(COMMAND_DELETED_EVENT, command);
  }

  return (
    <Modal
      ref={props.ref}
      id="deleteCommandModal"
      modalTitle="Delete command"
      centered={true}
    >
      <div class="modal-body">
        <Show when={error() !== ""}>
          <div class="alert alert-danger" role="alert">
            {error()}
          </div>
        </Show>
        <div class="mb-3 row">
          <span>
            Do you really want to delete the command {command().getTitle()} ({command().getId()})?
          </span>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
          Cancel
        </button>
        <button
          type="button"
          onClick={handleDeleteCommand}
          class="btn btn-danger"
        >
          Delete
        </button>
      </div>
    </Modal>
  );
}

DeleteCommandModal.Handler = new ModalHandler();
DeleteCommandModal.setCommand = setCommand;
DeleteCommandModal.onCommandDeleted = (callback) =>
  eventEmitter.on(COMMAND_DELETED_EVENT, callback);

export default DeleteCommandModal;
