<script>
  import Icon from '$/client/components/Icon.svelte';
  import { onMount } from 'svelte';
  import { fade } from "svelte/transition";
  import { log } from "$/client/logging.js";
  import api from '$/client/api.js';

  export let shown = true;
  let errors = [];

  $: has_errors = errors.length > 0;

  const rephresh = async () => {
    let [status, data] = await api.get('/api/devtools/info');

    if(status === 200) {
      errors = data.errors;
      log.debug("errors", errors);
    } else {
      log.error("Failed getting /api/devtools/devinfo", status, data);
    }
  }

  const handle_keypress = (event) => {
    if(event.ctrlKey && event.altKey) {
      if(event.key == "b" || event.keyCode == 66) {
        rephresh();
        shown = !shown;
      }
    } else if(event.key === "Escape") {
      shown = false;
    }
  }

  onMount(() => rephresh());
</script>

<svelte:window on:keydown={ handle_keypress } />

<style>
  bando {
    display: grid;
    grid-template-rows: 1fr;
    grid-template-columns: repeat(5, 1fr);
    grid-gap: 0.5rem;
    width: 450px;
    position: fixed;
    bottom: 0;
    right: 1rem;
    background-color: var(--red);
    opacity: 1;
    z-index: 10000;
    padding: 1rem;
    color: var(--value9);
    border-radius: var(--border-radius) var(--border-radius) 0 0;
  }

  bando#errors {
    display: flex;
    align-items: start;
    justify-content: start;
  }

  bando#errors ul {
    margin: 0px;
    padding: 0.3em;
    list-style-type: none;
  }

  bando a {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    color: var(--value9);
    width: min-content;
  }

</style>

{#if shown}
<bando transition:fade|local>
  <a href="/admin/#/icons/">
    <Icon name="feather" light={ true } size="64" />
    <span>Icons</span>
  </a>
  <a href="/admin/#/bando/components/">
    <Icon name="layout" light={ true } size="64" />
    <span>Library</span>
  </a>
  <a href="/admin/#/djenterator/">
    <Icon name="edit" light={ true } size="64" />
    <span>Templates</span>
  </a>
  <a href="/admin/#/routes/">
    <Icon name="code" light={ true } size="64" />
    <span>Routes</span>
  </a>
  <a href="/admin/#/errors/">
    <Icon name="alert-circle" light={ true } size="64" />
    <span>Errors</span>
  </a>
</bando>
{:else if has_errors}
  <bando id="errors" transition:fade|local>
    <a href="/admin/#/errors/">
      <Icon name="alert-circle" light={ true } size="64" />
      <span>Errors</span>
    </a>
    <ul>
      {#each errors as error, i}
        <li>{ error.location.file}</li>
      {/each}
    </ul>
  </bando>
{/if}
