<script lang="ts">
  import { timefmt } from '../../../helpers.js';
  export let hash: string;
  export let id: string;
  export let disc: number;
  export let timestamp: number;
  export let pushed_by: string;
  export let removed: number | undefined;
  export let can_add: boolean = false;
  export let can_remove: boolean = false;
  export let owner: string;
  export let repo: string;
  export let token: string;
  export let authors: {
    login?: string;
    name?: string;
    key: string;
  }[] = [];
  export let header:
    | {
        message: string;
        timestamp: string;
      }
    | undefined;

  console.log('HEADER', JSON.stringify(header));
</script>

<div class={'py-3 flex' + (removed ? ' opacity-50' : '')} id="{hash}.{timestamp}">
  <div class="px-3 w-20">
    <a href="/{pushed_by}">
      <img class="profile-picture-small" src="/identicon/{pushed_by}/small" alt={pushed_by} />
    </a>
  </div>
  <div class="w-full flex flex-col">
    <div class="flex justify-between items-center mb-2">
      <div class="grow-1 align-middle">
        <a class="author" href="/{pushed_by}">{pushed_by}</a> added a change {timefmt(
          timestamp * 1000
        )}
      </div>
      {#if removed && can_add}
        <div class="ms-2">
          <form action="/api/discussion/{owner}/{repo}/{disc}/add_change" method="POST">
            <input type="hidden" name="discussion_change" value={id} />
            <input type="hidden" name="token" value={token} />
            <button class="btn btn-sm btn-primary">Add back</button>
          </form>
        </div>
      {/if}
      {#if !removed && can_remove}
        <div class="ms-2">
          <form action="/api/discussion/{owner}/{repo}/{disc}/remove_change" method="POST">
            <input type="hidden" name="discussion_change" value={id} />
            <input type="hidden" name="token" value={token} />
            <button class="btn btn-sm btn-error">Remove from discussion</button>
          </form>
        </div>
      {/if}
    </div>
    <div>
      {#if header}
        <a href="/{owner}/{repo}/change/{hash}">
          {#if header.message.length}
            {header.message}
          {:else}
            <em>(no change message)</em>
          {/if}
        </a>{#each authors as auth}
          {#if auth.login}
            , by <a class="author" href="/{auth.login}">{auth.login}</a>
          {:else if auth.key}
            , by <span class="key break-all">{auth.key}</span>
          {/if}
        {/each}{#if header.timestamp}
          , created {timefmt(Date.parse(header.timestamp))}
        {/if}
      {/if}
      <div class="p-1 break-all">
        <code class="hash">{hash}</code>
      </div>
    </div>
  </div>
</div>

<style>
  .profile-picture-small {
    width: 4em;
    background-color: white;
    border-radius: 50%;
  }
</style>