<script>
	import { _ } from "svelte-i18n";
	import store from "../../store";
	import { UserGroupService } from "@odit/lfk-client-js";
	import toast from "svelte-french-toast";

	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) {
			toast($_("updating-group"));
			UserGroupService.userGroupControllerPut(original_data.id, editable)
				.then((resp) => {
					Object.assign(original_data, editable);
					original_data = editable;
					Object.assign(original_data, editable);
					toast.success($_("group-updated"));
				})
				.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"></li>
						<li class="flex items-center">
							<a class="mr-2" href="../"
								><svg
									xmlns="http://www.w3.org/2000/svg"
									width="24"
									height="24"
									viewBox="0 0 24 24"
									fill="none"
									stroke="currentColor"
									stroke-width="2"
									stroke-linecap="round"
									stroke-linejoin="round"
									class="inline-block"
									><path d="m12 19-7-7 7-7" /><path d="M19 12H5" /></svg
								>
								{$_("groups")}</a
							>
						</li>
					</ol>
				</nav>
			</div>
		</div>
		<div class="mb-4 text-3xl font-extrabold leading-tight">
			{editable.name}
			<div 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: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: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:w-auto sm:text-sm mb-1 lg:mb-0"
						>{$_("save-changes")}</button
					>
				{/if}
			</div>
		</div>
		<!--  -->
		<div class="text-sm w-full mt-2">
			<label for="title" class="font-semibold 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-neutral-800 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 mt-2">
			<label for="groupdescription" class="font-semibold text-gray-700"
				>{$_("description")}</label
			>
			<input
				autocomplete="off"
				placeholder={$_("description")}
				type="text"
				bind:value={editable.description}
				name="groupdescription"
				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-neutral-800 rounded-md p-2"
			/>
		</div>
		<div class="text-sm w-full mt-2">
			<p class="font-semibold mb-4">
				{$_("permissions")}
			</p>
			<div>
				<a
					class="px-4 py-2 bg-gray-500 rounded-md text-white"
					href="/groups/{params.groupid}/permissions/"
					>{$_("edit-permissions")}</a
				>
			</div>
			<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-neutral-800 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}
