import {SharedConsts} from "../shared/SharedConsts.js";
import {UtilApplications} from "./UtilApplications.js";
import {UtilList2} from "./UtilList2.js";
import {AppFilterBasic} from "./FilterApplications.js";
import {Util} from "./Util.js";

class ActorItemCleaner extends Application {
	// region External
	static pHandleButtonClick (evt, app, $html, data) {
		const instance = new ActorItemCleaner(app.actor);
		instance.render(true);
	}
	// endregion

	constructor (actor) {
		super({
			title: "Item Cleaner",
			template: `${SharedConsts.MODULE_LOCATION}/template/ActorItemCleaner.hbs`,
			width: 480,
			height: Util.getMaxWindowHeight(),
			resizable: true,
		});

		this._actor = actor;

		// Local fields
		this._pageFilter = new AppFilterBasic();

		this._list = null;
		this._$btnReset = null;
		this._$iptSearch = null;
	}

	_handleFilterChange () {
		const f = this._pageFilter.filterBox.getValues();
		this._list.filter(li => this._pageFilter.toDisplay(f, this._rows[li.ix]));
	}

	activateListeners ($html) {
		super.activateListeners($html);

		this._activateListeners_initBtnRun($html);
		this._activateListeners_initBtnReset($html);
		this._activateListeners_pInitListAndFilters($html);
	}

	_activateListeners_initBtnRun ($html) {
		$html.find(`[name="btn-run"]`).click(async () => {
			if (!this._list) return;

			const selIds = this._list.items
				.filter(it => $(it.ele).find(`input`).prop("checked"))
				.map(it => ({name: it.name, id: it.values.id}));

			const pluralStr = selIds.length !== 1 ? "s" : "";
			const doDelete = await UtilApplications.pGetConfirmation({
				title: `Delete Item${pluralStr}`,
				content: `<h3>Are you sure?</h3><p>${selIds.length} item${pluralStr} and ${pluralStr ? "their" : "its"} data will be permanently deleted.</p>`,
				confirmText: "Delete",
				faIcon: "fa-trash",
			});
			if (!doDelete) return;

			this.close();

			await this._actor.deleteEmbeddedDocuments("Item", selIds.map(it => it.id));
			ui.notifications.info(`Deleted ${selIds.length} item${selIds.length === 1 ? "" : "s"}`);
		});
	}

	_activateListeners_initBtnReset ($html) {
		this._$btnReset = $html.find(`[name="btn-reset"]`).click(() => {
			$html.find(`.search`).val("");
			if (this._list) this._list.reset();
		});
	}

	_activateListeners_pInitListAndFilters ($html) {
		this._$iptSearch = $html.find(`.search`);

		// Init list library
		this._list = new List({
			$iptSearch: this._$iptSearch,
			$wrpList: $html.find(`.veapp__list`),
		});
		SortUtil.initBtnSortHandlers($html.find(`[data-name="wrp-btns-sort"]`), this._list);
		ListUiUtil.bindSelectAllCheckbox($html.find(`[name="cb-select-all"]`), this._list);

		return this._pageFilter.pInitFilterBox({
			$iptSearch: this._$iptSearch,
			$btnReset: this._$btnReset,
			$btnOpen: $html.find(`[name=btn-filter]`),
			$btnToggleSummaryHidden: $html.find(`[name=btn-toggle-summary]`),
			$wrpMiniPills: $html.find(`.fltr__mini-view`),
			namespace: `tool-actor-item-cleaner`,
		}).then(() => {
			this._rows.forEach(it => this._pageFilter.addToFilters(it));

			this._list.doAbsorbItems(
				this._rows,
				{
					fnGetName: it => it.name,
					fnGetValues: it => ({id: it.id}),
					fnGetData: UtilList2.absorbFnGetData,
					fnBindListeners: it => UtilList2.absorbFnBindListeners(this._list, it),
				},
			);

			this._list.init();

			this._pageFilter.filterBox.render();

			this._pageFilter.filterBox.on(
				FilterBox.EVNT_VALCHANGE,
				this._handleFilterChange.bind(this),
			);

			this._handleFilterChange();
		});
	}

	/**
	 * Used by template engine.
	 */
	getData () {
		this._rows = this._actor.items.map((it, ix) => ({
			name: it.name,
			id: it.id,
			type: MiscUtil.get(it, "data", "type"),
			ix,
		}));

		return {
			...super.getData(),
			rows: this._rows,
		};
	}

	close (...args) {
		this._pageFilter.teardown();
		return super.close(...args);
	}
}

export {ActorItemCleaner};
