import { createResource, onMount } from "solid-js";
import List from "../../components/list";
import RemotesService from "../../services/remotes-service";
import CreateCommandModal from "../../modals/create-command-modal";
import DeleteCommandModal from "../../modals/delete-command-modal";

function CommandsList(props) {
  const [commands, { refetch: refetchCommands }] = createResource(
    RemotesService.getCommands
  );

  onMount(() => {
    refetchCommands();
  });

  CreateCommandModal.onCommandCreated(() => {
    refetchCommands();
  });
  
  DeleteCommandModal.onCommandDeleted(() => {
    refetchCommands();
  });

  function handleNewCommand() {
    refetchCommands();
    CreateCommandModal.Handler.show();
  }
  
  function handleDeleteCommand(command) {
    DeleteCommandModal.setCommand(command);
    DeleteCommandModal.Handler.show();
  }

  return (
    <>
      <div class="d-flex flex-row">
        <div class="d-flex flex-row flex-fill">
          {props.navigation ? props.navigation : null}
        </div>
        <div class="d-flex flex-row justify-content-end flex-fill">
          <button class="btn btn-dark me-2 mb-3" onClick={handleNewCommand}>
            <i class="bi bi-plus-square me-2"></i>
            New Command
          </button>
        </div>
      </div>
      <List
        class={"flex-fill"}
        columns={[
          {
            id: "id",
            name: "id",
            width: 6,
          },
          {
            id: "title",
            name: "Title",
          },
          {
            id: "protocol",
            name: "Protocol",
            width: 10,
          },
          {
            id: "type",
            name: "Type",
            width: 6,
          },
          {
            id: "options",
            name: "",
            width: 4,
          },
        ]}
        items={(commands() || []).map((command) => ({
          id: {
            html: <span class="font-monospace">{command.getId()}</span>,
          },
          title: {
            text: command.getTitle(),
          },
          protocol: {
            text: command.getProtocol(),
          },
          type: {
            text: command.getCommandType(),
          },
          options: {
            html: (
              <>
                <button
                  class="btn btn-sm btn-outline-secondary me-2"
                  onClick={(event) => {
                    event.stopPropagation();
                    handleDeleteCommand(command);
                  }}
                >
                  <i class="bi bi-trash-fill"></i>
                </button>
              </>
            ),
          },
          command,
        }))}
      ></List>
    </>
  );
}

export default CommandsList;
