<script>
  import { _ } from "svelte-i18n";
  import store from "../../store";
  import {
    UserGroupService
  } from "@odit/lfk-client-js";
  import Toastify from "toastify-js";
  import PromiseError from "../base/PromiseError.svelte";
  let data_loaded = false;
  export let params;
  const promise = UserGroupService.userGroupControllerGetOne(params.groupid);
  const colors = [
    "#f3558e",
    "#17b978",
    "#3498db",
    "#3f3b3b",
    "#775ada",
    "#7ed6df_#000000",
    "#000000",
    "#21e6c1_#000000",
    "#c0392b",
    "#d35400",
    "#7f8c8d",
    "#6ab04c",
    "#4834d4",
    "#ff1f5a",
    "#eac100",
  ];
  let matched_colors = [];
  $: delete_triggered = false;
  $: search_permission = "";
  $: original_data = {};
  $: editable = {};
  $: changes_performed = !(JSON.stringify(original_data) == JSON.stringify(editable));
  $: isGroupnameValid = editable.name !== "";
  $: save_enabled =
    changes_performed && isGroupnameValid 
  promise.then((data) => {
    let current_target = "";
    let colorindex = -1;
    data.permissions = data.permissions.sort();
    data.permissions.forEach((p) => {
      const target = p.split(":")[0];
      if (current_target !== p.split(":")[0]) {
        colorindex++;
        current_target = p.split(":")[0];
      }
      let background = colors[colorindex];
      let foreground = "#fff";
      if (background.includes("_")) {
        foreground = background.split("_")[1];
        background = background.split("_")[0];
      }
      matched_colors[target] = [background, foreground];
    });
    data_loaded = true;
    original_data = Object.assign(original_data, data);
    editable = Object.assign(editable, original_data);
  });
  function submit() {
    if (data_loaded === true && save_enabled) {
      Toastify({
        text: $_('updateing-group'),
        duration: 2500,
      }).showToast();
      UserGroupService.userGroupControllerPut(original_data.id, editable)
        .then((resp) => {
          Object.assign(original_data, editable);
          original_data = editable;
          Object.assign(original_data, editable);
          Toastify({
            text: $_('group-updated'),
            duration: 2500,
            backgroundColor: "linear-gradient(to right, #00b09b, #96c93d)",
          }).showToast();
        })
        .catch((err) => {});
    } else {
    }
  }
  function deleteGroup() {
    UserGroupService.userGroupControllerRemove(original_data.id, true)
      .then((resp) => {
        location.replace("./");
      })
      .catch((err) => {});
  }
</script>

{#await promise}
  {$_('loading-group-detail')}
{:then}
  <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"></path></svg>
            </li>
            <li class="flex items-center">
              <a class="mr-2" href="../">{$_('groups')}</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">{editable.name}</span>
            </li>
          </ol>
        </nav>
      </div>
    </div>
    <div class="mb-8 text-3xl font-extrabold leading-tight">
      {original_data.name}
      <span data-id="group_actions_${editable.id}">
        {#if store.state.jwtinfo.userdetails.permissions.includes('USERGROUP:DELETE')}
          {#if delete_triggered}
            <button
              on:click={deleteGroup}
              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-deletion')}</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-group')}</button>
          {/if}
        {/if}
        {#if !delete_triggered}
          <button
            disabled={!save_enabled}
            class:opacity-50={!save_enabled}
            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="text-sm w-full">
      <label
        for="title"
        class="font-medium text-gray-700">{$_('name')}</label>
      <input
        autocomplete="off"
        placeholder={$_('name')}
        type="text"
        bind:value={editable.name}
        class:border-red-500={!isGroupnameValid}
        class:focus:border-red-500={!isGroupnameValid}
        class:focus:ring-red-500={!isGroupnameValid}
        name="title"
        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 rounded-md p-2" />
      {#if !isGroupnameValid}
        <span
          class="flex items-center font-medium tracking-wide text-red-500 text-xs mt-1 ml-1">
          {$_('group-name-is-required')}
        </span>
      {/if}
    </div>
    <div class="text-sm w-full">
      <label
        for="firstname"
        class="font-medium text-gray-700">{$_('description')}</label>
      <input
        autocomplete="off"
        placeholder={$_('description')}
        type="text"
        bind:value={editable.description}
        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 rounded-md p-2" />
    </div>
    <div class="text-sm w-full mt-8">
      <p class="font-medium mb-4">
        {$_('permissions')}
        <a
          class="px-4 py-2 bg-gray-500 rounded-md text-white"
          href="/groups/{params.groupid}/permissions/">{$_('edit-permissions')}</a>
      </p>
      <div class="w-full sm:my-px sm:px-px sm:w-1/2">
        <input
          autocomplete="off"
          placeholder="{$_('search-for-permission')}"
          type="text"
          bind:value={search_permission}
          class="mt-4 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>
      {#each original_data.permissions as p}
        {#if p.toLowerCase().includes(search_permission.toLowerCase())}
          <span
            style="background:{matched_colors[p.split(':')[0]][0]};color:{matched_colors[p.split(':')[0]][1]};"
            class="mt-1 inline-flex items-center justify-center px-2 py-1 text-xs font-bold leading-none text-indigo-100 rounded">{p}</span>
          <!--  -->
        {/if}
      {/each}
    </div>
  </section>
{:catch error}
  <PromiseError {error} />
{/await}
