import type { VNode } from 'vue';
import type { DropdownButtonItemArgs } from '../dropdown-button/dropdown-button-item';
import type { FormItemWrapperArgs, MarginType } from '../form/form-item-wrapper';
import { Prop, toNative } from 'vue-facing-decorator';
import DropdownList from '.';
import TsxComponent, { Component } from '../../app/vuetsx';
import { isNullOrEmpty } from '../../common/utils/is-null-or-empty';
import { LanguageUtils } from '../../common/utils/language-utils';

interface LanguageDropdownArgs extends FormItemWrapperArgs {
	value?: LanguageUtils.LanguageListItem;
	placeholder?: string;
	customOptions?: LanguageUtils.LanguageListItem[];
	changed?: (newValue: LanguageUtils.LanguageListItem) => void;
}

const getFlaggedResult = (h, item): any => {
	if (item.dataRow != null) {
		return (
			<span>
				<img class="flag" src={LanguageUtils.getLanguageFlagUrl(item.dataRow.flag, false)} />
&nbsp;&nbsp;
				{item.dataRow.text}
			</span>
		);
	}

	return (<span>{item.text || ''}</span>);
};

@Component
class LanguageDropdownComponent extends TsxComponent<LanguageDropdownArgs> implements LanguageDropdownArgs {
	@Prop() label!: string | VNode;
	@Prop() labelButtons!: DropdownButtonItemArgs[];
	@Prop() value!: LanguageUtils.LanguageListItem;
	@Prop() marginType?: MarginType;
	@Prop() placeholder!: string;
	@Prop() mandatory!: boolean;
	@Prop() wrap!: boolean;
	@Prop() hint: string;
	@Prop() subtitle!: string;
	@Prop() appendIcon: string;
	@Prop() prependIcon: string;
	@Prop() customOptions: LanguageUtils.LanguageListItem[];
	@Prop() appendClicked: () => void;
	@Prop() prependClicked: () => void;
	@Prop() changed: (newValue: LanguageUtils.LanguageListItem) => void;

	raiseChangeEvent(e) {
		this.populateValidationDeclaration();

		if (this.changed != null) {
			this.changed(e);
		}
	}

	render(h) {
		return (
			<DropdownList
				options={!isNullOrEmpty(this.customOptions)
					? [
							...this.customOptions,
							...LanguageUtils.getLanguageList(),
						]
					: LanguageUtils.getLanguageList()}
				displayMember="text"
				valueMember="id"
				customRenderOption={(
					h,
					item,
					o,
				) => { return getFlaggedResult(h, item); }}
				customRenderSelectionResult={(
					h,
					item,
					o,
				) => { return getFlaggedResult(h, item); }}
				wrap={this.wrap}
				mandatory={this.mandatory}
				label={this.label}
				labelButtons={this.labelButtons}
				subtitle={this.subtitle}
				selected={this.value}
				hint={this.hint}
				appendIcon={this.appendIcon}
				prependIcon={this.prependIcon}
				marginType={this.marginType}
				appendClicked={this.appendClicked}
				prependClicked={this.prependClicked}
				changed={e => this.raiseChangeEvent(e)}
			/>
		);
	}
}

const LanguageDropdown = toNative(LanguageDropdownComponent);
export default LanguageDropdown;
