import { createSignal } from "solid-js";
import List from "../../components/list";
import CreateDeviceModal from "../../modals/create-device-modal";
import DeviceService from "../../services/device-service";

function DevicesListView(props) {
  const [devices, setDevices] = createSignal([]);

  handleRefreshDevices();

  CreateDeviceModal.onDeviceCreated(() => {
    handleRefreshDevices();
  });

  function handleNewDevice() {
    CreateDeviceModal.Handler.show();
  }

  async function handleRefreshDevices() {
    let devices = await DeviceService.getDevices();
    setDevices(devices);
  }

  return (
    <div
      class={
        "d-flex flex-column overflow-hidden flex-fill px-3 pb-2 pt-3 " +
        props.class
      }
    >
      <div class="d-flex flex-row">
        {props.navigation}
        <div class="d-flex flex-row justify-content-end flex-fill">
          <button class="btn btn-dark me-2 mb-3" onClick={handleNewDevice}>
            <i class="bi bi-plus-square me-2"></i>
            New Device
          </button>
        </div>
      </div>
      <List
        onListItemClick={() => {}}
        items={devices().map((device) => ({
          id: {
            html: <span class="font-monospace">{device.getId()}</span>,
          },
          name: {
            text: device.getName(),
          },
          description: {
            text: device.getDescription(),
          },
          device,
        }))}
        class={"flex-fill"}
        columns={[
          {
            id: "id",
            name: "id",
            width: 6,
          },
          {
            id: "name",
            name: "Name",
            width: 10,
          },
          {
            id: "description",
            name: "Description",
          },
        ]}
      ></List>
    </div>
  );
}

export default DevicesListView;
