import { Teleport } from 'vue';
import VueEasyLightbox from 'vue-easy-lightbox';
import { Prop, toNative } from 'vue-facing-decorator';
import TsxComponent, { Component } from '../../app/vuetsx';
import { SlotNameIdentifier } from '../../common/slot-name-identifier';
import { PortalUtils } from '../../common/utils/utils';
import './css/lightbox.css';

interface LightboxItem {
	src: string;
	title: string;
}

interface LightboxArgs {
	imageArr: string[] | LightboxItem[];
	scrollDisabled?: boolean;
	moveDisabled?: boolean;
	rotateDisabled?: boolean;
	customPortalContainer?: string;
}

interface LightboxShowArgs {
	index?: number;
}

export class LightboxConfig {
	static defaultPortalTarget = 'body';
}

@Component({
	components: {
		'teleport': Teleport,
		'vue-easy-lightbox': VueEasyLightbox,
	},
})
class LightboxComponent extends TsxComponent<LightboxArgs> implements LightboxArgs {
	@Prop() imageArr: string[] | LightboxItem[];
	@Prop() scrollDisabled: boolean;
	@Prop({ default: true }) moveDisabled: boolean;
	@Prop({ default: true }) rotateDisabled: boolean;
	@Prop() customPortalContainer: string;
	visible: boolean = false;
	index: number = 0;
	everShown: boolean = false;

	show(args?: LightboxShowArgs) {
		args = args || {};

		const performShow = () => {
			if (args.index > -1) {
				this.index = args.index;
			}

			this.visible = true;
		};

		if (!this.everShown) {
			this.everShown = true;
			this.everShown = true;
			this.$nextTick(() => {
				performShow();
			});
		} else {
			performShow();
		}
	}

	hide() {
		this.visible = false;
	}

	private getInstance(): any {
		return this.$refs.lightboxInstance;
	}

	get portalContainer(): string {
		return this.customPortalContainer || LightboxConfig.defaultPortalTarget;
	}

	render(h) {
		return (
			<teleport to={this.portalContainer}>
				{this.everShown
				&& (
					<vue-easy-lightbox
						ref="lightboxInstance"
						scrollDisabled={this.scrollDisabled != null ? this.scrollDisabled : PortalUtils.treatAsMobileDevice()}
						moveDisabled={this.moveDisabled}
						rotateDisabled={this.rotateDisabled}
						imgs={this.imageArr}
						visible={this.visible}
						index={this.index}
						onHide={() => {
							try {
								this.index = this.getInstance().imgIndex;
							} catch (error) {
								this.index = 0;
							}

							this.visible = false;
						}}
					/>
				)}
			</teleport>
		);
	}
}

SlotNameIdentifier(LightboxComponent, 'Lightbox');
const Lightbox = toNative(LightboxComponent);
export default Lightbox;
