<script>
  import IoMdClipboard from 'svelte-icons/io/IoMdClipboard.svelte'
  import IoMdLink from 'svelte-icons/io/IoMdLink.svelte'
  import IoMdAlert from 'svelte-icons/io/IoMdAlert.svelte'
  import { writeText } from 'clipboard-polyfill';
  import { Button, TextField, Loading, Popover, PopoverButton, H2, FormField, FileInput, FileTile, Slider } from 'attractions';
  import Chart from './Chart.svelte';
  import { onMount } from 'svelte';
  import { currentChartID } from './stores';
  import { writable } from 'svelte/store';

  let isLoaded = false;
  let error = null;

  let name = '';
  let top = '';
  let left = '';
  let right = '';
  let bot = '';

  let images = writable([]);
  let currentImage = {
    file: null,
    name: '',
    x: 0.5,
    y: 0.5
  };

  let upload = null;
  let s;

  let submitError = null;

  onMount(() => {
    s = new WebSocket('wss://chartmaker.oat.zone/connect?id=' + $currentChartID);
    s.addEventListener('message', (e) => {
      let data = JSON.parse(e.data);
      console.log(data);
      if (!isLoaded) {
        name = data.name || '';
        top = data.topText || '';
        left = data.leftText || '';
        right = data.rightText || '';
        bot = data.bottomText || '';
        isLoaded = true;
      } else {
        for (const img of data) {
          img.file = 'https://chartmaker.oat.zone/img/' + img.file;
        }
        images.update(imgs => [...imgs, ...data]);
      }
    });
    s.addEventListener('error', (e) => {
      error = e;
    });
  });

  let submitting = false;

  async function submitImage() {
    submitting = true;
    let formData = new FormData();
    formData.append('id', $currentChartID);
    formData.append('name', currentImage.name);
    formData.append('x', currentImage.x);
    formData.append('y', currentImage.y);
    formData.append('icon', upload);

    try {
      const response = await fetch('https://chartmaker.oat.zone/add', {
        method: 'POST',
        mode: 'cors',
        body: formData,
      });

      if (response.ok) {
        submitting = false;
        currentImage = {file: null, name: '', x: 0.5, y: 0.5}
        upload = null;
      } else {
        submitting = false;
        if (response.body) {
          submitError = response.statusText + ': ' + await response.text();
        } else {
          submitError = response.statusText;
        }
      }
    } catch(err) {
      submitting = false;
    }
  }
</script>

<style>
  #clipboard {
    width: 450px;
    display: flex;
    align-items: flex-end;
    justify-content: center;
  }
  #theeverything {
    text-align: center;
		/*max-width: 680px;*/
		margin: 0 auto;
  }
  .center {
    width: 100%;
    display: flex;
    justify-content: center
  }

  #chart {
    width: 512px;
    height: auto;
  }

  #canvas {
    position: absolute;
  }

  #panels {
    display: flex;
    justify-content: center;
    gap: 0.5em;
    z-index: -9999;
  }

  .img-container {
    width: 64px;
    height: 64px;
    display: inline-block;
  }
  .img-file {
    width: auto;
    height: 100%;
  }

  .img {
    position: relative;
    width: 64px;
    height: 64px;
  }

  .img * {
    width: 64px;
    height: 64px;
  }

  .img *:last-child, .img *:last-child {
    z-index: 999;
    height: unset;
  }

  @media (max-width: 650px) {
    #panels {
      flex-direction: column;
    }
  }
</style>



<div id="theeverything">
  <div class="center">
    <div id="clipboard">
      <div style="flex-grow: 1">
        <TextField outline withItem value={window.location.toString()} disabled>
          <div style="width: 16px; height: 16px; display: inline-block" class="item"><IoMdLink/></div>
        </TextField>
      </div>
      <Button outline on:click={() => {writeText(window.location.toString())}}><div style="width: 19px; height: 19px; display: inline-block"><IoMdClipboard/></div></Button>
    </div>
  </div>

  {#if error}
    <div class="center">
      <div id="error">
        <div style="width: 16px; height: 16px; display: inline-block;"><IoMdAlert/></div>
        {error}
      </div>
    </div>
  {/if}

  {#if !isLoaded && !error}
    <br><br><br>
    <Loading/>
  {:else if isLoaded}
    <div class="center">
      <div>
        {#key name}
          {name}
        {/key}
        <div id="panels">
          <div id="chart">
            {#key top + left + right + bot}
              <div id="canvas"><Chart topText={top} leftText={left} rightText={right} bottomText={bot} fontSize=14/></div>
            {/key}
            {#each [...$images, currentImage] as img, i}
              {#if img && img.file}
                <div class="img" style="top: {Math.floor(img.y*512)-i*64}px; left: {Math.floor((img.x)*512)}px">
                  <Popover>
                    <div class="img-container">
                      <img class="img-file" src="{img.file}" alt="{img.name}">
                    </div>
                    <div slot="popover-content" class="popover-content">
                      <PopoverButton>{img.name}</PopoverButton>
                    </div>
                  </Popover>
                </div>
              {/if}
            {/each}
          </div>
          <div id="create">
            <H2>add an image</H2>

            <!-- svelte-ignore missing-declaration -->
            <FileInput bind:value={upload} accept="image/*" max={1} on:change={() => {
              const reader = new FileReader();
              reader.onload = (e) => {currentImage.file = e.target.result}
              reader.readAsDataURL(upload);
            }}/>
            {#if upload != null}
              <FileTile file={upload} on:delete={() => {upload = null; currentImage.file = null}}/>
            {/if}
            <br>
            <FormField
              name="Name"
              help="what's their name?"
            >
              <TextField bind:value={currentImage.name} placeholder="scrunkly" />
            </FormField>
            <FormField
              name="X Axis"
            >
              <Slider
                bind:value={currentImage.x}
                min={0}
                max={1}
                step={0.001}
                tooltips="active"
                ticks={{mode: 'step', step: 0.05, subDensity: 50}}
              />
            </FormField>
            <FormField
              name="Y Axis"
            >
              <Slider
                bind:value={currentImage.y}
                min={0}
                max={1}
                step={0.001}
                tooltips="active"
                ticks={{mode: 'step', step: 0.05, subDensity: 50}}
              />
            </FormField>

            <div class="center">
              <Button outline disabled={!(currentImage.name && currentImage.file) || submitting} on:click={submitImage}>
                add
              </Button>
            </div>

            {#if submitError}
              <div class="center">
                <div id="error">
                  <div style="width: 16px; height: 16px; display: inline-block;"><IoMdAlert/></div>
                  {submitError}
                </div>
              </div>
            {/if}
          </div>
        </div>
      </div>
    </div>
  {/if}
</div>
