import { sidebarTemplate } from "./scripts-funcs.js";

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

	for(let scope of data.scopes) {
		const btnSwitch = scope.state == "disabled"
			? `<button 
					class="btn btn-success btn-small change-state-btn" 
					data-scope='${JSON.stringify(scope)}'
					type="button"
					data-value="enable"
				>Enable</button>`
			: `<button 
					class="btn btn-warning btn-small change-state-btn" 
					data-scope='${JSON.stringify(scope)}'
					type="button"
					data-value="disable"
				>Disable</button>`;

		preparedData.push({
			name: scope.name,
			filename: `${scope.filename}<br><code><small>${scope.path}</small></code>`,
			state: Helper.template.toogleStateBadge(scope.state),
			actions: `
				${btnSwitch}
			`
		});
	}

	return preparedData;
}

function renderingMainTable(scr, data, total) {
	scr.currentScreen.DOMObject.querySelector(".main-container").innerHTML = Helper.template.table(
		"Scopes list", 
		{
			name: "Scope name", 
			filename: "Filename", 
			state: "State", 
			actions: "Actions"
		},
		data,
		`<span class="table-meta">Total: <span class="total">${total}</span> scopes</span>`
	);
}

function initMainTableInteractiveElements(scr, sh_api) {
	scr.currentScreen.DOMObject.querySelectorAll(".change-state-btn").forEach(btn => {
		btn.addEventListener("click", e => {
			const btn = e.currentTarget;
			if(btn.getAttribute("disabled")) {
				return ;
			}

			const methName = btn.dataset.value == "enable"
				? "scope_enable"
				: "scope_disable"

			const scope = JSON.parse(btn.dataset.scope);
			Helper.states.btnLoadingState(btn, true);
			sh_api.scripts[methName](scope.name, (err, data, meta) => {
				Helper.states.btnLoadingState(btn, false);

				if(data) {
					setTimeout(() => Screens.reinit(), 250);
					Toasts.createSuccess(
						`Request Success`,
						`State of <b>${scope.name}</b> was changed`
					).show();
				} else {
					Toasts.createError(
						"Request failed",
						`Scope state not changed`
					).show();
				}

			});
		});
	});
}

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

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

				renderingMainTable(scr, prepareData(resp.data), resp.data.total);
				initMainTableInteractiveElements(scr, sh_api);

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

export {
	scopes
}