<script lang="ts">
	import { getSelectedContext } from "$lib/contexts/SelectContext.svelte";
	import { getStateContext } from "$lib/contexts/StateContext.svelte";
	import type Device from "$lib/models/device";
	import { KELVIN_PALETTE, RGB_PALETTE } from "$lib/models/palette";
	import ColorPalette from "./ColorPalette.svelte";

  const {deviceList} = getStateContext();
  const {selectedMap} = getSelectedContext();
  
  let selected: Device[];
  let unselected: Device[];
  $: selected = $deviceList.filter(d => !!$selectedMap[d.id]);
  $: unselected = $deviceList.filter(d => !$selectedMap[d.id]);   

  let assignment: string;
  $: {
    assignment = "";
    if (selected.length > 0) {
      for (const alias of selected[0].aliases) {
        if (!selected.find(d => !d.aliases.includes(alias)) && !unselected.find(d => d.aliases.includes(alias))) {
          assignment = alias;
          break;
        }
      }

      if (assignment === "") {
        if (selected.length == 1) {
          assignment = selected[0].id;
        } else {
          let prefix = selected[0].id;
          for (const device of selected) {
            for (let i = 0; i < prefix.length; i++) {
              if (device.id.charAt(i) !== prefix.charAt(i)) {
                prefix = prefix.slice(0, i);
                break;
              }
            }
          }

          if (prefix.length > 0) {
            assignment = `${prefix}{${selected.map(d => d.id.slice(prefix.length)).join("|")}}`
          }
        }

        if (assignment === "") {
          assignment = `{${selected.map(d => d.id).join("|")}}`
        }
      }
    }
  }
</script>

<div class="toolbar">
  <ColorPalette palette={RGB_PALETTE} />
</div>

<style lang="sass">
  div.toolbar
    position: fixed
    bottom: 0

    width: 100%
    height: 2em
    padding: 0.35em 1ch
    box-sizing: border-box
    font-size: 1.5em
    background: #18181c
    color: #abc
    box-shadow: 1px 1px 1px #000

    display: flex
    flex-direction: row
    flex-wrap: wrap
</style>
