<script lang="typescript" context="module">
  import type { AppSession, PageData, PreloadContext } from "src/utils/session";
  export async function preload(
    this: PreloadContext,
    { path }: PageData,
    session: AppSession
  ) {
    const result = await this.fetch("/rules/md", { credentials: "include" });
    const md = (await result.json()) as Option<MDText, { error: string }>;
    if (md.ok) {
      return { rulesText: md.text };
    }
    return { rulesText: "" };
  }
</script>

<script lang="typescript">
  import { onMount } from "svelte";
  import "easymde/dist/easymde.min.css";
  import { fade } from "svelte/transition";
  import type { MDText } from "./md";
  import { Option } from "@shared/common/async_utils";

  export let rulesText!: string;
  let vpHeight: number;
  let textArea!: HTMLTextAreaElement;
  let statusMessage: string = "";
  let error = false;
  onMount(async () => {
    const EasyMDE = (await import("easymde")).default;
    let mde = new EasyMDE({
      element: textArea,
      previewClass: "md-dark md-editor-preview md-body",
      forceSync: true,
      initialValue: rulesText,
    });
  });

  async function save() {
    const result = await fetch("/rules/md", {
      credentials: "include",
      method: "post",
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json",
      },
      body: JSON.stringify({ text: textArea.value } as MDText),
    });
    const opt = (await result.json()) as Option<unknown, { error: string }>;

    let waitTime = 2000;
    if (opt.ok) {
      statusMessage = "Saved!";
      error = false;
    } else {
      statusMessage = opt.error;
      error = true;
      waitTime = 10000;
    }
    setTimeout(() => {
      statusMessage = "";
      error = false;
    }, waitTime);
  }
</script>

<style>
  @import "./markdown-dark.css";
  @import "./easymde-style.css";

  .viewport {
    @apply bg-gray-800 rounded-sm px-20 py-5 shadow-lg w-screen pt-10;
    height: 100vh;
  }

  span.status {
    @apply text-white px-4;

    &.error {
      @apply text-red-600;
    }
  }

  .save-button {
    @apply text-base bg-green-600 p-2 px-3 text-white rounded-sm;

    &:hover {
      @apply bg-green-800 text-gray-100 cursor-pointer;
    }
  }

  :global .CodeMirror-scroll {
    max-height: calc(90vh - 250px) !important;
    min-height: calc(90vh - 250px) !important;
  }

  @screen lg {
    .viewport {
      @apply w-3/4;
      height: 80vh;
    }

    :global .CodeMirror-scroll {
      max-height: calc(70vh - 250px) !important;
      min-height: calc(70vh - 250px) !important;
    }
  }

  #easy-mde {
    visibility: hidden;
  }
</style>

<svelte:head>
  <title>Edit rules</title>
</svelte:head>
<div class="viewport" bind:clientHeight={vpHeight}>
  <h1 class="text-white text-4xl font-light py-2">Edit rules</h1>
  <form on:submit|preventDefault={save}>
    <p class="text-white md-editor">
      <textarea id="easy-mde" bind:this={textArea} />
    </p>
    <span class="float-right">
      {#if statusMessage}
        <span
          transition:fade={{ duration: 100 }}
          class="status {error ? 'error' : ''}">{statusMessage}</span>
      {/if}
      <input type="submit" class="save-button" value="Save" />
    </span>
  </form>
</div>
