import {SharedConsts} from "../shared/SharedConsts.js";
import {Vetools} from "./Vetools.js";
import {Util} from "./Util.js";
import {UtilApplications} from "./UtilApplications.js";

class Charactermancer_Race_Util {
	static async pPostLoadBrew (fileData) {
		const out = [];

		if (fileData.race) out.push(...Renderer.race.mergeSubraces(fileData.race, {isAddBaseRaces: true}));

		if (fileData.subrace) {
			const baseList = (await Vetools.pGetRaces({isAddBaseRaces: true})).race;
			baseList.forEach(it => PageFilterRaces.mutateForFilters(it));

			const nxtData = Renderer.race.adoptSubraces(baseList, fileData.subrace);
			const mergedNxtData = Renderer.race.mergeSubraces(nxtData);

			out.push(...mergedNxtData);
		}

		return out;
	}
}

class Charactermancer_Race_FeatSelect extends BaseComponent {
	// region External
	static async pGetUserInput (featCount) {
		if (!featCount) return {isFormComplete: true, data: {}};
		const comp = new this({featCount});
		return UtilApplications.pGetImportCompApplicationFormData({
			comp,
			height: Util.getMaxWindowHeight(featCount * 360),
		});
	}
	// endregion

	/**
	 * @param opts
	 * @param opts.featCount
	 */
	constructor (opts) {
		opts = opts || {};
		super();

		this._featCount = opts.featCount;
	}

	get modalTitle () { return `Choose Feat${this._featCount === 1 ? "" : "s"}`; }

	static _getProps (ix) {
		return {
			propFeatData: `featData_${ix}`,
		}
	}

	render ($wrp) {
		const $rows = [...new Array(this._featCount)].map((_, ix) => {
			const {propFeatData} = this.constructor._getProps(ix);

			const $btnSelectFeat = $(`<button class="btn btn-default">Select Feat</button>`)
				.click(async () => {
					const {ImportListFeat} = await import("./ImportListFeat.js");

					const featData = await ImportListFeat.UserChoose.pGetUserChoice(
						{
							id: "feats-raceFeatSelect",
							name: "Feats",
							singleName: "Feat",

							wizardTitleWindow: "Select Source",
							wizardTitlePanel3: "Configure and Open List",
							wizardTitleButtonOpenImporter: "Open List",
						},
						"raceFeatSelect",
					);
					if (!featData) return;
					this._state[propFeatData] = featData;
				});

			const $dispFeat = $(`<div class="flex-col overflow-y-auto min-h-0"></div>`);
			const hkFeatData = () => {
				$dispFeat.empty();
				const featMeta = this._state[propFeatData]?.flags?.[SharedConsts.MODULE_NAME_FAKE];
				if (!featMeta) return $dispFeat.html(`<div class="italic ve-muted">No feat selected</div>`);

				const {page, source, hash} = featMeta;

				Renderer.hover.pCacheAndGet(page, source, hash)
					.then(loadedFeat => {
						$dispFeat.html(Vetools.withUnpatchedDiceRendering(() => Renderer.hover.$getHoverContent_stats(UrlUtil.PG_FEATS, loadedFeat)));
					});
			};
			this._addHookBase(propFeatData, hkFeatData);
			hkFeatData();

			return $$`<div class="flex-col min-h-0">
				${ix === 0 ? `` : `<hr class="hr-2">`}

				<div class="flex-v-center mb-2">${$btnSelectFeat}</div>

				${$dispFeat}
			</div>`
		});

		$$($wrp)`
			${$rows}
		`;
	}

	pGetFormData () {
		const out = [];

		let isComplete = true;

		[...new Array(this._featCount)].map((_, ix) => {
			const {propFeatData} = this.constructor._getProps(ix);

			const featMeta = this._state[propFeatData]?.flags?.[SharedConsts.MODULE_NAME_FAKE];
			if (!featMeta) return isComplete = false;

			const {page, source, hash} = featMeta;

			out.push({page, source, hash});
		});

		return {
			isFormComplete: isComplete,
			data: out,
		};
	}

	_getDefaultState () {
		return {}
	}
}

class Charactermancer_Race_SizeSelect extends BaseComponent {
	// region External
	static async pGetUserInput ({sizes}) {
		if (!sizes || !sizes.length) return {isFormComplete: true, data: SZ_MEDIUM};
		const comp = new this({sizes});
		if (comp.isNoChoice()) return comp.pGetFormData();
		return UtilApplications.pGetImportCompModalFormData({comp});
	}
	// endregion

	/**
	 * @param opts
	 * @param opts.sizes
	 */
	constructor (opts) {
		opts = opts || {};
		super();

		this._sizes = opts.sizes || [SZ_MEDIUM];
	}

	get modalTitle () { return `Choose Size`; }

	render ($wrp) {
		if (this._sizes.length === 1) {
			$wrp.append(`<div>${Parser.sizeAbvToFull(this._sizes[0])}</div>`);
			return;
		}

		ComponentUiUtil.$getSelEnum(
			this,
			"size",
			{
				values: this._sizes,
				isAllowNull: true,
				fnDisplay: Parser.sizeAbvToFull,
			},
		)
			.appendTo($wrp);
	}

	isNoChoice () { return this._sizes.length <= 1; }

	pGetFormData () {
		return {
			isFormComplete: this._state.size != null,
			data: this._sizes.length === 1 ? this._sizes[0] : this._state.size,
		};
	}
}

export {
	Charactermancer_Race_Util,
	Charactermancer_Race_FeatSelect,
	Charactermancer_Race_SizeSelect,
}
