import { createSignal } from "solid-js";
import Remote from "../data/remote.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 [remote, setRemote] = createSignal(new Remote());
const eventEmitter = new EventEmitter();
const REMOTE_DELETED_EVENT = "success";

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

  async function handleDeleteRemote() {
    try {
      await RemotesService.deleteRemote(remote().getId());
    } catch (e) {
      setError(e.message);
      throw e;
    }
    DeleteRemoteModal.Handler.hide();
    eventEmitter.dispatchEvent(REMOTE_DELETED_EVENT, remote);
  }

  return (
    <Modal
      ref={props.ref}
      id="deleteRemoteModal"
      modalTitle="Delete remote"
      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 remote {remote().getTitle()} ({remote().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={handleDeleteRemote}
          class="btn btn-danger"
        >
          Delete
        </button>
      </div>
    </Modal>
  );
}

DeleteRemoteModal.Handler = new ModalHandler();
DeleteRemoteModal.setRemote = setRemote;
DeleteRemoteModal.onRemoteDeleted = (callback) =>
  eventEmitter.on(REMOTE_DELETED_EVENT, callback);

export default DeleteRemoteModal;
