import { createMemo, createResource, createSignal, onMount } from "solid-js";
import List from "../../components/list";
import RemotesService from "../../services/remotes-service";
import CreateRemoteModal from "../../modals/create-remote-modal";
import DeleteRemoteModal from "../../modals/delete-remote-modal";
import FileUtils from "../../tools/file-utils";
import Serializer from "../../data/serializer";
import RemoteService from "../../services/remotes-service";

function RemotesList(props) {
  const [remotes, { refetch: refetchRemotes }] = createResource(
    RemotesService.getRemotes
  );
  const [selectedRemotes, setSelectedRemotes] = createSignal([]);
  const canExport = createMemo(() => selectedRemotes().length > 0);

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

  CreateRemoteModal.onRemoteCreated(() => {
    refetchRemotes();
  });

  DeleteRemoteModal.onRemoteDeleted(() => {
    refetchRemotes();
  });

  function handleNewRemote() {
    CreateRemoteModal.Handler.show();
  }

  function handleDeleteRemote(remote) {
    DeleteRemoteModal.setRemote(remote);
    DeleteRemoteModal.Handler.show();
  }

  function handleListItemsSelect(items) {
    setSelectedRemotes(items.map((item) => item.remote));
  }

  async function handleExport() {
    let remotes = await Promise.all(
      selectedRemotes().map((remote) => RemoteService.getRemote(remote.getId()))
    );
    let files = remotes.map((remote) =>
      FileUtils.createJsonFile(
        Serializer.serializeRemote(remote),
        `${remote.getTitle()}.remote.json`
      )
    );
    if (files.length >= 1) {
      FileUtils.downloadFile(files[0]);
    }
  }

  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"
            disabled={!canExport()}
            onClick={handleExport}
          >
            <i class="bi bi-box-arrow-up me-2"></i>
            Export
          </button>
          <button class="btn btn-dark me-2 mb-3" onClick={handleNewRemote}>
            <i class="bi bi-plus-square me-2"></i>
            New
          </button>
        </div>
      </div>
      <List
        class={"flex-fill"}
        columns={[
          {
            id: "id",
            name: "id",
            width: 6,
          },
          {
            id: "title",
            name: "Title",
          },
          {
            id: "options",
            name: "",
            width: 4,
          },
        ]}
        onListItemClick={() => {}}
        onListItemsSelect={handleListItemsSelect}
        items={(remotes() || []).map((remote) => ({
          id: {
            html: <span class="font-monospace">{remote.getId()}</span>,
          },
          title: {
            text: remote.getTitle(),
          },
          options: {
            html: (
              <>
                <button
                  class="btn btn-sm btn-outline-secondary me-2"
                  onClick={(event) => {
                    event.stopPropagation();
                    handleDeleteRemote(remote);
                  }}
                >
                  <i class="bi bi-trash-fill"></i>
                </button>
              </>
            ),
          },
          remote,
        }))}
      ></List>
    </>
  );
}

export default RemotesList;
