<script lang="ts">
  import Lamp from "$lib/components/Lamp.svelte";
	import MetaLamp from "$lib/components/MetaLamp.svelte";
	import RoomHeader from "$lib/components/RoomHeader.svelte";
	import { getModalContext } from "$lib/contexts/ModalContext.svelte";
	import { getSelectedContext } from "$lib/contexts/SelectContext.svelte";
	import { getStateContext } from "$lib/contexts/StateContext.svelte";
	import DeviceModal from "$lib/modals/DeviceModal.svelte";
	import QuickAssignModal from "$lib/modals/QuickAssignModal.svelte";
	import ScriptModal from "$lib/modals/ScriptModal.svelte";
	import TriggerModal from "$lib/modals/TriggerModal.svelte";

  const {selectedList, toggleMultiSelection} = getSelectedContext();
  const {roomList, deviceList} = getStateContext();
  const {modal} = getModalContext();

  function handleKeyPress(e: KeyboardEvent) {
    if ($modal.kind === "closed" && !e.ctrlKey && !e.shiftKey) {
      switch (e.key.toLocaleLowerCase()) {
        case 'e':
          if ($selectedList.length) {
            modal.set({kind: "device.edit", op: "none"});
            e.preventDefault();
          }
          break;
        case 'o':
          modal.set({kind: "script.edit"});
          e.preventDefault();
          break;
        case 't':
          modal.set({kind: "trigger.edit"});
          e.preventDefault();
          break;
        case 'c':
          if ($selectedList.length) {
            modal.set({kind: "device.quickassign"});
            e.preventDefault();
          }
          break;
        case 'a':
          if ($selectedList.length > 0) {
            toggleMultiSelection($selectedList);
          } else {
            toggleMultiSelection($deviceList.map(d => d.id));
          }
          break;
      }
    }
  }
</script>

<svelte:body on:keypress={handleKeyPress} />

<div class="page">
  {#each $roomList as room (room.name)}
    <div class="room">
      <RoomHeader 
        devices={[...room.devices, ...room.groups.flatMap(g => g.devices)]} 
        name={room.name}
      />
      <div class="devices">
        {#each room.devices as device (device.id) }
          <Lamp device={device} />
        {/each}
      </div>
      <div class="devices">
        {#each room.groups as group (group.name)}
          <MetaLamp name={group.name} devices={group.devices} />
        {/each}
      </div>
    </div>
  {/each}
</div>

<DeviceModal />
<ScriptModal />
<TriggerModal />
<QuickAssignModal />

<style>
  div.page {
    margin: 0 auto;
    width: 200ch;
    max-width: 95%;
    margin-top: 1em;
    font-size: 1.33rem;
  }

  div.room {
    margin-bottom: 1rem;
  }

  div.devices { 
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
  }
  div.devices + div.devices {
    margin-top: 0.25em;
  }
</style>