function sidebarTemplate(active) {
	return Helper.template.sidebarNav([
		{
			content: `<span class="list-label"><i class="ph ph-cpu"></i> Scopes</span>`,
			route: "/#!/scripts/scopes",
			is_active: active == "scopes"
		},
		{
			content: `<span class="list-label"><i class="ph ph-play"></i> Actions</span>`,
			route: "/#!/scripts/actions",
			is_active: active == "actions"
		},
		{
			content: `<span class="list-label"><i class="ph ph-magnifying-glass"></i> Regular</span>`,
			route: "/#!/scripts/regular",
			is_active: active == "regular"
		}
	]);
}

function runActionScript(sh_api, alias, cb) {
	sh_api.scripts.run({
		alias: alias,
		params: {}
	}, (err, data, meta) => {
		if(data) {
			cb(true);

			setTimeout(() => Screens.reinit(), 1000);

			setTimeout(() => Toasts.createSuccess(
				`${alias} running`,
				`<b>${alias}</b> running success`
			).show(), 300);
		} else {
			cb(false);

			setTimeout(() => Toasts.createError(
				`${alias} failed`,
				`<b>${alias}</b> running failed`
			).show(), 300);
		}
	});
}

function createActionCardHtml(action) {
	const cardColor = action.state == "enabled" ? "primary" : "warning";
	return `
		<div 
			class="card device-action card-${cardColor} script-action" 
			data-alias="${action.alias}"
		>
			<span class="card-title">${action.name} 
				<button 
					class="btn-icon without-hover action-details-btn" 
					data-alias='${action.alias}'
				>
					<i class="ph ph-dots-three-vertical"></i>
				</button>
			</span>

			<div class="card-content">
				<div class="device-icon-container">
					<div class="device-icon">
						${action.icon}
					</div>
				</div>

				<div class="device-name mb-2">${action.description}</div>
			</div>
		</div>
	`;
}

function setActionCardEventsHandlers(sh_api, actionCard) {
	actionCard.querySelector(".card-content").addEventListener("click", e => {
		if(actionCard.getAttribute("disabled")) {
			return ;
		}

		Helper.states.cardScriptActionLoadingState(actionCard, true);

		const alias = actionCard.dataset.alias;
		runActionScript(sh_api, alias, resultFlag => {
			Helper.states.cardScriptActionLoadingState(actionCard, false);

			if(resultFlag) {
				actionCard.classList.add("card-success");
				setTimeout(() => actionCard.classList.remove("card-success"), 1000);
			}
		});

	});
}

function createActionCard(sh_api, action) {
	const container = document.createElement("div");
	container.innerHTML = createActionCardHtml(action);
	const card = container.querySelector(".card");
	setActionCardEventsHandlers(sh_api, card);

	return card;
}

export {
	sidebarTemplate,
	runActionScript,
	createActionCardHtml,
	setActionCardEventsHandlers,
	createActionCard,
}