<script>
    import {fade} from 'svelte/transition';
    
    export let article_data;
    
    const actions = [
      {name: 'Mark as good (and skip to next)', kbd: 'A'},
      {name: 'Mark as bad (and skip to next)', kbd: 'B'},
      {name: 'Upload related file', kbd: 'R'},
      {name: 'Skip', kbd: 'ctrl'},
    ]

    const toast_states = {
      'success' : {class: 'alert-success', text: 'Article updated successfully'},
      'error' : {class: 'alert-error', text: 'Article update failed'},
    }
    let toast_state = {};
    let toast_visible = false;

    
    function onKeyDown(e) {apiAction(e.key)}
    function apiAction(key) {
      if (actions.map(d => d.kbd.toLowerCase()).includes(key.toLowerCase())){ // ignore other keypresses

        const updateArticle = (async() => {
          const response = await fetch('/api/article/' + article_data.id + '/set', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({
              'action': key.toLowerCase(),
            })
          })
          const success = response.status == 200;
        
          if (success){
            showToast('success');
          } else {
            showToast('error');
          }

        })()
      }
    }

    function showToast(state){  
      toast_visible = true;
      toast_state = toast_states[state];
      setTimeout(() => {
        toast_visible = false;
      }, 1000)

    }
</script>


<div class="card bg-neutral-300 shadow-xl">
    <div class="card-body">
      <h2 class="card-title">Your options: (click on action or use keyboard)</h2>
      <div class="overflow-x-auto">
        <table class="table w-full table-compact">
          <!-- head -->
          <thead>
            <tr>
                <th>Action</th>
                <th>Keyboard shortcut</th>
            </tr>
          </thead>
          <tbody>
            {#each actions as action}
                
                <tr>
                    <td><button on:click={() => apiAction(action.kbd)}>{ action.name }</button></td>
                    <td><kbd class="kbd">{ action.kbd }</kbd></td>
                </tr>
            
            {/each}
          </tbody>
        </table>
      </div>
    </div>
</div>

<svelte:window on:keydown|preventDefault={onKeyDown} />

{#if toast_visible}
<div class="toast" transition:fade>
  <div class="alert { toast_state.class }">
      <div>
      <span>{ toast_state.text }.</span>
      </div>
  </div>
</div>
{/if}