<script>
  import { _ } from 'svelte-i18n'
	import NavigationBar from './components/General/NavigationBar.svelte';
  import Clock from './components/General/Clock.svelte'
  import Preparation from './components/Preparation/Preparation.svelte';
  import Animation from './components/Animation/Animation.svelte';
  import Settings from './components/Settings/Settings.svelte';
  import Devices from './components/Devices/Devices.svelte';
  import Show from './components/Show/Show.svelte';
  import GeneralConsole from './components/Console/GeneralConsole.svelte';
  import RoundIconButton from './components/General/RoundIconButton.svelte';
  import { generateToast, showInformation, needProjectSave, peripherals } from './stores';
  import { SaveProject } from '../wailsjs/go/main/App.js';
  import { construct_svelte_component } from 'svelte/internal';
  import { EventsOn } from '../wailsjs/runtime'
  import { CreateProject } from "../wailsjs/go/main/App";
  import { WindowSetTitle } from "../wailsjs/runtime/runtime"
  import { get } from "svelte/store"
  import ToastNotification from './components/General/ToastNotification.svelte';

  // Handle the event when a new peripheral is detected
  EventsOn('PERIPHERAL_ARRIVAL', function(peripheralInfo){
        // When a new peripheral is detected, add it to the map and:
        // - Pass the isDetected key to true
        // - Set the isSaved key to the last value
        let peripheralsList = get(peripherals)
        let lastSavedProperty = peripheralsList[peripheralInfo.SerialNumber]?.isSaved
        peripheralInfo.isDetected = true
        peripheralInfo.isSaved = (lastSavedProperty === true) ? true : false
        peripherals.update((peripherals) => {
          peripherals[peripheralInfo.SerialNumber] = peripheralInfo
          return {...peripherals}
        })
        console.log("Hardware has been added to the system");
        generateToast('info', 'bxs-hdd', $_("peripheralArrivalToast") + ' <b>' + peripheralInfo.Name + '</b>')
  })

  // Handle the event when a peripheral is removed from the system
  EventsOn('PERIPHERAL_REMOVAL', function(peripheralInfo){
      console.log("Hardware has been removed from the system");
      // When a peripheral is disconnected, pass its isDetected key to false
      // If the isSaved key is set to false, we can completely remove the peripheral from the list
      let peripheralsList = get(peripherals)
      let lastSavedProperty = peripheralsList[peripheralInfo.SerialNumber]?.isSaved
      let needToDelete = (lastSavedProperty !== true) ? true : false
      peripherals.update((storedPeripherals) => {
        if (needToDelete){
          delete storedPeripherals[peripheralInfo.SerialNumber];
          return { ...storedPeripherals };
        }
        storedPeripherals[peripheralInfo.SerialNumber].isDetected = false
        return {...storedPeripherals}
      })
      generateToast('warning', 'bxs-hdd', $_("peripheralRemovalToast") + ' <b>' + peripheralInfo.Name + '</b>')
  })

  // Handle the event when a peripheral status is updated
  EventsOn('PERIPHERAL_STATUS', function(peripheral, status){
      console.log("Hardware status has been updated to " + status);
      // When a peripheral status is updated, update it in the store
      peripherals.update((storedPeripherals) => {
          return {
          ...storedPeripherals,
          [peripheral.SerialNumber]: {
              ...storedPeripherals[peripheral.SerialNumber],
              isSaved: true,
              Status: status,
          },
      }})
  })

  // Set the window title
  $: {
    WindowSetTitle("DMXConnect - " + $showInformation.Name + ($needProjectSave ? " (" + $_("unsavedProjectFlag") + ")" : ""))
  }

  let selectedMenu = "settings"
  // When the navigation menu changed, update the selected menu
	function onNavigationChanged(event){
    selectedMenu = event.detail.menu;
	}

  // Save the project
  function saveProject(){
    SaveProject().then((filePath) => {
      needProjectSave.set(false)
      console.log("Project has been saved to " + filePath)
      generateToast('info', 'bxs-save', $_("projectSavedToast"))
    }).catch((error) => {
      console.error(`Unable to save the project: ${error}`)
      generateToast('danger', 'bx-error', $_("projectSaveErrorToast") + ' ' + error)
    })
  }

  // Handle window shortcuts
  document.addEventListener('keydown', function(event) {
      // Check the CTRL+S keys
      if ((event.ctrlKey || event.metaKey) && event.key === 's') {
          // Avoid the natural behaviour
          event.preventDefault();
          // Save the current project
          saveProject()
      }
  });

</script>

<header>
    <NavigationBar on:navigationChanged="{onNavigationChanged}"/>
    {#if $needProjectSave}
      <RoundIconButton on:mouseup={saveProject} icon="bx-save" width="2.5em" tooltip={$_("saveButtonTooltip")}></RoundIconButton>
    {/if}
    <Clock/>
</header>
<main>
	{#if selectedMenu === "settings"}
  <Settings />
  {:else if selectedMenu === "devices"}
  <Devices />
  {:else if selectedMenu === "preparation"}
  <Preparation />
  {:else if selectedMenu === "animation"}
  <Animation />
  {:else if selectedMenu === "show"}
  <Show />
  {:else if selectedMenu === "console"}
  <GeneralConsole />
  {/if}
  <ToastNotification/>
</main>

<style>
	main {
		text-align: left;
		padding: 1em;
		max-width: 240px;
		margin: 0 auto;
	}

	@media (min-width: 640px) {
		main {
			max-width: none;
		}
	}
</style>