<script>
  import { _ } from "svelte-i18n";
  import lodashIsEqual from "lodash.isequal";
  import store from "../store";
  import { UserService, UserGroupService } from "@odit/lfk-client-js";
  import "gridjs/dist/theme/mermaid.css";
  import Toastify from "toastify-js";
  import PromiseError from "./PromiseError.svelte";
  export let params;
  const user_promise = UserService.userControllerGetOne(params.userid);
  let data_loaded = false;
  $: delete_triggered = false;
  $: original_data = {};
  $: editable_userdata = undefined;
  $: allgroups = [];
  $: allgroups_ids = [];
  $: usergroups_array = [];
  user_promise.then((data) => {
    console.log(data);
    data_loaded = true;
    original_data = Object.assign(original_data, data);
    editable_userdata = data;
    usergroups_array = [];
    allgroups.forEach((g) => {
      allgroups_ids.push(g.id);
    });
  });
  UserGroupService.userGroupControllerGetAll().then((data) => {
    console.log(data);
    allgroups = data;
  });
  $: changes_performed = !lodashIsEqual(original_data, editable_userdata);
  function updateGroups() {
    console.log("updating groups...");
    console.log(editable_userdata.groups);
    allgroups.forEach((g) => {
      const exists_in_currentstate = editable_userdata.groups.some(
        (obj) => obj.id === g.id
      );
      console.log("exists:" + exists_in_currentstate);
      if (exists_in_currentstate === true) {
        editable_userdata.groups = editable_userdata.groups.filter(function (
          obj
        ) {
          return obj.id !== g.id;
        });
      } else {
        console.log("add to arr:" + g.id);
        editable_userdata.groups.push(g);
      }
    });
    console.log("new groups:");
    console.log(editable_userdata.groups);
  }
  function submit() {
    if (data_loaded === true && changes_performed === true) {
      console.log("ok, submitting...");
      console.log(editable_userdata);
      Toastify({
        text: $_("updating-user"),
        duration: 2500,
      }).showToast();
      UserService.userControllerPut(original_data.id, editable_userdata)
        .then((resp) => {
          console.log(resp);
          Object.assign(original_data, editable_userdata);
          original_data = editable_userdata;
          Object.assign(original_data, editable_userdata);
          //
          Toastify({
            text: $_("user-updated"),
            duration: 2500,
            backgroundColor: "linear-gradient(to right, #00b09b, #96c93d)",
          }).showToast();
        })
        .catch((err) => {
          console.log(err);
        });
    } else {
      console.log("no changes performed");
    }
  }
  function deleteUser() {
    UserService.userControllerRemove(original_data.id, true)
      .then((resp) => {
        console.log(resp);
        location.replace("./");
      })
      .catch((err) => {
        console.log(err);
      });
  }
</script>

{#await user_promise}
  <!--  -->
{:then user}
  <section class="container p-5 select-none">
    <div class="flex flex-row mb-4">
      <div class="w-full">
        <nav class="w-full flex">
          <ol class="list-none flex flex-row items-center justify-start">
            <li class="flex items-center">
              <svg
                class="flex-shrink-0 w-5 h-5 mr-2"
                fill="currentColor"
                width="24"
                height="24"
                xmlns="http://www.w3.org/2000/svg"
                viewBox="0 0 640 512"><path
                  fill="currentColor"
                  d="M610.5 341.3c2.6-14.1 2.6-28.5 0-42.6l25.8-14.9c3-1.7 4.3-5.2 3.3-8.5-6.7-21.6-18.2-41.2-33.2-57.4-2.3-2.5-6-3.1-9-1.4l-25.8 14.9c-10.9-9.3-23.4-16.5-36.9-21.3v-29.8c0-3.4-2.4-6.4-5.7-7.1-22.3-5-45-4.8-66.2 0-3.3.7-5.7 3.7-5.7 7.1v29.8c-13.5 4.8-26 12-36.9 21.3l-25.8-14.9c-2.9-1.7-6.7-1.1-9 1.4-15 16.2-26.5 35.8-33.2 57.4-1 3.3.4 6.8 3.3 8.5l25.8 14.9c-2.6 14.1-2.6 28.5 0 42.6l-25.8 14.9c-3 1.7-4.3 5.2-3.3 8.5 6.7 21.6 18.2 41.1 33.2 57.4 2.3 2.5 6 3.1 9 1.4l25.8-14.9c10.9 9.3 23.4 16.5 36.9 21.3v29.8c0 3.4 2.4 6.4 5.7 7.1 22.3 5 45 4.8 66.2 0 3.3-.7 5.7-3.7 5.7-7.1v-29.8c13.5-4.8 26-12 36.9-21.3l25.8 14.9c2.9 1.7 6.7 1.1 9-1.4 15-16.2 26.5-35.8 33.2-57.4 1-3.3-.4-6.8-3.3-8.5l-25.8-14.9zM496 368.5c-26.8 0-48.5-21.8-48.5-48.5s21.8-48.5 48.5-48.5 48.5 21.8 48.5 48.5-21.7 48.5-48.5 48.5zM96 224c35.3 0 64-28.7 64-64s-28.7-64-64-64-64 28.7-64 64 28.7 64 64 64zm224 32c1.9 0 3.7-.5 5.6-.6 8.3-21.7 20.5-42.1 36.3-59.2 7.4-8 17.9-12.6 28.9-12.6 6.9 0 13.7 1.8 19.6 5.3l7.9 4.6c.8-.5 1.6-.9 2.4-1.4 7-14.6 11.2-30.8 11.2-48 0-61.9-50.1-112-112-112S208 82.1 208 144c0 61.9 50.1 112 112 112zm105.2 194.5c-2.3-1.2-4.6-2.6-6.8-3.9-8.2 4.8-15.3 9.8-27.5 9.8-10.9 0-21.4-4.6-28.9-12.6-18.3-19.8-32.3-43.9-40.2-69.6-10.7-34.5 24.9-49.7 25.8-50.3-.1-2.6-.1-5.2 0-7.8l-7.9-4.6c-3.8-2.2-7-5-9.8-8.1-3.3.2-6.5.6-9.8.6-24.6 0-47.6-6-68.5-16h-8.3C179.6 288 128 339.6 128 403.2V432c0 26.5 21.5 48 48 48h255.4c-3.7-6-6.2-12.8-6.2-20.3v-9.2zM173.1 274.6C161.5 263.1 145.6 256 128 256H64c-35.3 0-64 28.7-64 64v32c0 17.7 14.3 32 32 32h65.9c6.3-47.4 34.9-87.3 75.2-109.4z" /></svg>
            </li>
            <li class="flex items-center">
              <a class="mr-2" href="./">{$_('users')}</a><svg
                stroke="currentColor"
                fill="none"
                stroke-width="2"
                viewBox="0 0 24 24"
                stroke-linecap="round"
                stroke-linejoin="round"
                class="h-3 w-3 mr-2 stroke-current"
                height="1em"
                width="1em"
                xmlns="http://www.w3.org/2000/svg"><line
                  x1="5"
                  y1="12"
                  x2="19"
                  y2="12" />
                <polyline points="12 5 19 12 12 19" /></svg>
            </li>
            <li class="flex items-center">
              <span class="mr-2">{original_data.firstname}
                {original_data.middlename || ''}
                {original_data.lastname}</span>
            </li>
          </ol>
        </nav>
      </div>
    </div>
    <div class="mb-8 text-3xl font-extrabold leading-tight">
      {original_data.firstname}
      {original_data.middlename || ''}
      {original_data.lastname}
      <span data-id="user_actions_${editable_userdata.id}">
        {#if store.state.jwtinfo.userdetails.permissions.includes('USER:DELETE')}
          {#if delete_triggered}
            <button
              on:click={deleteUser}
              class="w-full justify-center rounded-md border border-transparent shadow-sm px-4 py-2 bg-red-600 text-base font-medium text-white hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500 sm:ml-3 sm:w-auto sm:text-sm">{$_('confirm-delete')}</button>
            <button
              on:click={() => {
                delete_triggered = !delete_triggered;
              }}
              class="w-full justify-center rounded-md border border-transparent shadow-sm px-4 py-2 bg-blue-400 text-base font-medium text-white sm:w-auto sm:text-sm">{$_('cancel')}</button>
          {/if}
          {#if !delete_triggered}
            <button
              on:click={() => {
                delete_triggered = true;
              }}
              type="button"
              class="w-full justify-center rounded-md border border-transparent shadow-sm px-4 py-2 bg-red-600 text-base font-medium text-white hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500 sm:ml-3 sm:w-auto sm:text-sm">{$_('delete-user')}</button>
          {/if}
        {/if}
        {#if !delete_triggered}
          <button
            disabled={!changes_performed}
            class:opacity-50={!changes_performed}
            type="button"
            on:click={submit}
            class="w-full justify-center rounded-md border border-transparent shadow-sm px-4 py-2 bg-blue-600 text-base font-medium text-white hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 sm:ml-3 sm:w-auto sm:text-sm">{$_('save-changes')}</button>
        {/if}
      </span>
    </div>

    <!--  -->
    <div class="mt-2 flex items-center">
      <img
        alt={$_('profile-picture')}
        class="inline-block h-20 w-20 rounded-full overflow-hidden bg-gray-100"
        src={editable_userdata.profilePic} />
      <!-- <span
        class="inline-block h-12 w-12 rounded-full overflow-hidden bg-gray-100"><svg
          class="h-full w-full text-gray-300"
          fill="currentColor"
          viewBox="0 0 24 24"><path
            d="M24 20.993V24H0v-2.996A14.977 14.977 0 0112.004 15c4.904 0 9.26 2.354 11.996 5.993zM16.002 8.999a4 4 0 11-8 0 4 4 0 018 0z" /></svg></span> -->
      <button
        type="button"
        class="ml-5 bg-white py-2 px-3 border border-gray-300 rounded-md shadow-sm text-sm leading-4 font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500">Change</button>
    </div>
    <!--  -->
    <div class="mt-3 text-sm w-full">
      <input
        id="enabled"
        on:change={() => {
          editable_userdata.enabled = !editable_userdata.enabled;
          // TODO: this reactive set does not work?
        }}
        name="enabled"
        type="checkbox"
        checked={editable_userdata.enabled}
        class="focus:ring-indigo-500 h-4 w-4 text-indigo-600 border-gray-300 rounded" />
      <label
        for="enabled"
        class="ml-1 font-medium text-gray-700">Active?</label>
      <p class="text-gray-500">set the user active/ inactive</p>
    </div>
    <div class="text-sm w-full">
      <label
        for="firstname"
        class="font-medium text-gray-700">{$_('first-name')}</label>
      <input
        autocomplete="off"
        placeholder={$_('first-name')}
        type="text"
        bind:value={editable_userdata.firstname}
        name="firstname"
        class="mt-1 focus:ring-indigo-500 focus:border-indigo-500 block w-full shadow-sm rounded-l-md sm:text-sm border-gray-300 border bg-gray-50 text-gray-500 dark:bg-gray-900 dark:text-gray-100 rounded-md p-2" />
    </div>
    <div class="text-sm w-full">
      <label
        for="middlename"
        class="font-medium text-gray-700">{$_('middle-name')}</label>
      <input
        autocomplete="off"
        placeholder={$_('middle-name')}
        type="text"
        bind:value={editable_userdata.middlename}
        name="middlename"
        class="mt-1 focus:ring-indigo-500 focus:border-indigo-500 block w-full shadow-sm rounded-l-md sm:text-sm border-gray-300 border bg-gray-50 text-gray-500 dark:bg-gray-900 dark:text-gray-100 rounded-md p-2" />
    </div>
    <div class="text-sm w-full">
      <label
        for="lastname"
        class="font-medium text-gray-700">{$_('last-name')}</label>
      <input
        autocomplete="off"
        placeholder={$_('last-name')}
        type="text"
        bind:value={editable_userdata.lastname}
        name="lastname"
        class="mt-1 focus:ring-indigo-500 focus:border-indigo-500 block w-full shadow-sm rounded-l-md sm:text-sm border-gray-300 border bg-gray-50 text-gray-500 dark:bg-gray-900 dark:text-gray-100 rounded-md p-2" />
    </div>
    <div class="text-sm w-full">
      <label
        for="email"
        class="font-medium text-gray-700">{$_('e-mail-adress')}</label>
      <input
        autocomplete="off"
        placeholder={$_('e-mail-adress')}
        type="email"
        bind:value={editable_userdata.email}
        name="email"
        class="mt-1 focus:ring-indigo-500 focus:border-indigo-500 block w-full shadow-sm rounded-l-md sm:text-sm border-gray-300 border bg-gray-50 text-gray-500 dark:bg-gray-900 dark:text-gray-100 rounded-md p-2" />
    </div>
    <div class="text-sm w-full">
      <label
        for="username"
        class="font-medium text-gray-700">{$_('username')}</label>
      <input
        autocomplete="off"
        placeholder={$_('username')}
        type="text"
        bind:value={editable_userdata.username}
        name="username"
        class="mt-1 focus:ring-indigo-500 focus:border-indigo-500 block w-full shadow-sm rounded-l-md sm:text-sm border-gray-300 border bg-gray-50 text-gray-500 dark:bg-gray-900 dark:text-gray-100 rounded-md p-2" />
    </div>
    <div class="text-sm w-full">
      <span class="font-medium">{$_('groups')}</span>
      <!-- svelte-ignore a11y-no-onchange -->
      <select
        on:change={updateGroups}
        bind:value={usergroups_array}
        class="mt-1 focus:ring-indigo-500 focus:border-indigo-500 block w-full shadow-sm rounded-l-md sm:text-sm border-gray-300 border bg-gray-50 text-gray-500 dark:bg-gray-900 dark:text-gray-100 rounded-md p-2"
        multiple>
        {#each allgroups as g}
          {#if editable_userdata.groups.some((obj) => obj.id === g.id)}
            <option selected value={g.id}>{g.name}</option>
          {:else}
            <option value={g.id}>{g.name}</option>
          {/if}
        {/each}
      </select>
    </div>
    <div class="text-sm w-full">
      <span class="font-medium">Permissions</span>
      <div
        class="border-4 border-dashed rounded h-96 mb-4 p-5 text-lg text-center">
        <!--  -->
        <div class="flex flex-wrap -mx-1 overflow-hidden">
          <div class="my-1 px-1 w-full overflow-hidden sm:w-1/2">
            <button
              type="button"
              class="w-full justify-center rounded-md border border-transparent shadow-sm px-4 py-2 bg-gray-600 text-base font-medium text-white hover:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-500 sm:ml-3 sm:w-auto sm:text-sm">&gt;</button>
          </div>

          <div class="my-1 px-1 w-full overflow-hidden sm:w-1/2">
            <button
              type="button"
              class="w-full justify-center rounded-md border border-transparent shadow-sm px-4 py-2 bg-gray-600 text-base font-medium text-white hover:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-500 sm:ml-3 sm:w-auto sm:text-sm">&lt;</button>
          </div>
        </div>
        <!--  -->
        <div class="flex flex-wrap -mx-1 overflow-hidden">
          <div class="my-1 px-1 w-full overflow-hidden sm:w-1/2">
            <div
              class="border-4 border-dashed rounded mb-4 p-5 text-lg text-center">
              <p
                class="block w-full mt-1 text-sm dark:border-gray-600 dark:bg-gray-700 bg-gray-200 p-2 focus:border-purple-400 focus:outline-none focus:shadow-outline-purple dark:text-gray-300 dark:focus:shadow-outline-gray form-input">
                DEMO_PERMISSION
              </p>
              <p
                class="block w-full mt-1 text-sm dark:border-gray-600 dark:bg-gray-700 bg-gray-200 p-2 focus:border-purple-400 focus:outline-none focus:shadow-outline-purple dark:text-gray-300 dark:focus:shadow-outline-gray form-input">
                DEMO_PERMISSION
              </p>
            </div>
          </div>

          <div class="my-1 px-1 w-full overflow-hidden sm:w-1/2">
            <div
              class="border-4 border-dashed rounded mb-4 p-5 text-lg text-center">
              <p
                class="block w-full mt-1 text-sm dark:border-gray-600 dark:bg-gray-700 bg-gray-200 p-2 focus:border-purple-400 focus:outline-none focus:shadow-outline-purple dark:text-gray-300 dark:focus:shadow-outline-gray form-input">
                DEMO_PERMISSION
              </p>
              <p
                class="block w-full mt-1 text-sm dark:border-gray-600 dark:bg-gray-700 bg-gray-200 p-2 focus:border-purple-400 focus:outline-none focus:shadow-outline-purple dark:text-gray-300 dark:focus:shadow-outline-gray form-input">
                DEMO_PERMISSION
              </p>
            </div>
          </div>
        </div>
        TODO: permission picker 🔒
      </div>
    </div>
  </section>
{:catch error}
  <PromiseError {error} />
{/await}
