<script lang="ts">
  import { goto } from "$app/navigation";
  import { getStores } from "$app/stores";

  import { sl3 } from "$lib/clients/sl3";
  import Modal from "$lib/components/common/Modal.svelte";
  import ModalBody from "$lib/components/common/ModalBody.svelte";
  import { getModalContext } from "$lib/components/contexts/ModalContext.svelte";
  import { getProjectContext } from "$lib/components/contexts/ProjectContext.svelte";
  import { getProjectListContext } from "$lib/components/contexts/ProjectListContext.svelte";
  import { getScopeContext } from "$lib/components/contexts/ScopeContext.svelte";
  import StatusSelect from "$lib/components/controls/StatusSelect.svelte";
  import type Project from "$lib/models/project";
  import type { ProjectEntry, ProjectInput, Requirement, RequirementInput } from "$lib/models/project";
  import Status from "$lib/models/status";
  import { projectPrettyId, scopePrettyId } from "$lib/utils/prettyIds";

  const {currentModal, closeModal} = getModalContext();
  const {scope} = getScopeContext();
  const {reloadProject} = getProjectContext();
  const {reloadProjectList} = getProjectListContext();
  const {page} = getStores();

  let project: ProjectInput
  let projectId: number
  let oldStats: RequirementInput["stats"]

  let error: string
  let loading: boolean
  let show: boolean
  let op: "Create" | "Edit" | "Delete"

  $: switch ($currentModal.name) {
    case "project.create":
      initCreate();
      op = "Create";
      break;

    case "project.edit":
      initEdit($currentModal.project);
      op = "Edit";
      break;

    default:
      loading = false;
      error = null;
      show = false;
  }

  function initCreate() {
    project = {
      name: "",
      description: "",
      status: Status.Available,
      createdTime: void(0),
    }

    show = true;
  }

  function initEdit(current: Project) {
    project = {
      name: current.name,
      description: current.description,
      status: current.status,
    }

    projectId = current.id;
    show = true;
  }

  async function submit() {
    error = null;
    loading = true;

    try {
      switch (op) {
        case "Create":
          const newProject = await sl3(fetch, $page.stuff.idToken).createProject($scope.id, project);
          projectId = newProject.id
          break;
        case "Edit":
          await sl3(fetch, $page.stuff.idToken).updateProject($scope.id, projectId, project);
          break;
      }
        
      // Wait for project to reload
      await reloadProject();
      await reloadProjectList();

      goto(`/${scopePrettyId($scope)}/projects/${projectPrettyId({id: projectId, name: project.name})}`, {replaceState: op === "Edit"})

      closeModal();
    } catch(err) {
      if (err.statusCode != null) {
        error = err.statusMessage;
      } else {
        error = err
      }

    } finally {
      loading = false;
    }
  }
</script>

<form on:submit|preventDefault={submit}>
  <Modal show={show} closable verb={op} noun="Project" disabled={loading} error={error}>
    <ModalBody>
      <label for="name">Name</label>
      <input name="name" type="text" bind:value={project.name} />
      <label for="description">Description</label>
      <textarea name="description" bind:value={project.description} />
      <label for="stats">Status</label>
      <StatusSelect bind:status={project.status} />
    </ModalBody>
  </Modal>
</form>