import { 
	sidebarTemplate, 
	runActionScript, 
	setActionCardEventsHandlers, 
	createActionCardHtml,
} from "./scripts-funcs.js";
import { actionDetailsPopup } from "./scripts-action-popup.js";

function prepareData(data) {
	const preparedData = [];

	for(let script of data.scripts) {
		preparedData.push({
			alias: script.alias,
			author: script.created_by,
			name: script.name,
			icon: script.icon ?? '<i class="ph ph-play"></i>',
			description: script.description,
			filename: `${script.filename}<br><code><small>${script.path}</small></code>`,
			state: script.state,
			code: script.code,
			id: script.id ?? 0,
			area_id: script.area_id ?? -1
		});
	}

	return preparedData;
}

function renderingMainGrid(scr, data, total) {
	let grid = `<div class="f-grid g-5 w-100">`;

	const provideSciptsData = {};

	for(let item of data) {
		provideSciptsData[item.alias] = item;
		grid += createActionCardHtml(item);
	}
	grid += `</div>`;

	const mainContainer = scr.currentScreen.DOMObject.querySelector(".main-container");
	mainContainer.innerHTML = grid;
	scr.currentScreen.DOMObject.provideSciptsData = provideSciptsData;
}

function initMainGridInteractiveElements(scr, sh_api) {
	scr.currentScreen.DOMObject.querySelectorAll(".script-action").forEach(actionCard => {
		setActionCardEventsHandlers(sh_api, actionCard);
	});

	scr.currentScreen.DOMObject.querySelectorAll(".action-details-btn").forEach(btn => {
		btn.addEventListener("click", e => {
			const btn = e.currentTarget;
			const script = scr.currentScreen.DOMObject.provideSciptsData[btn.dataset.alias] ?? {};

			console.log("SCRIPT", script);
			actionDetailsPopup(script, sh_api).show();
		});
	});
}

function actions(sh_api) {
	return {
		title: "Scripts Actions",
		alias: "scripts-actions",
		renderer: () => {
			return Helper.template.mainTemplate(sidebarTemplate("actions"));
		},
		initer: scr => {
			sh_api.scripts.actions_list((err, resp, meta) => {
				console.log("sh_api.scripts.actions_list", err, resp, meta);

				if(meta.status_code != 200) {
					return scr.error("Server API ERROR", "");
				}

				renderingMainGrid(scr, prepareData(resp.data), resp.data.total);
				initMainGridInteractiveElements(scr, sh_api);

				scr.ready();
			});			
		}
	}
}

export {
	actions,
	prepareData
}