/**
 * Created by rockyl on 2019-11-20.
 */
import injectProp = engine.injectProp;

export default class BuriedPoint extends engine.ScriptBase {
	static id = 'buried-point';

	@engine.dirtyFieldTrigger
	dpm: string = 'appID.0.0.0';
	@engine.dirtyFieldTrigger
	dcm: string = '202.projectID.0.0';
	@engine.dirtyFieldTrigger
	dom: string = '0.0.0.0';

	id: string;
	autoExposure: boolean = true;
	onceAutoExposure: boolean = false;
	autoExposureType: string = 'visible';
	autoClick: boolean = true;
	checkFps: number = 5;

	private _autoExposured = false;
	private _hostVisible = false;
	private _timer;

	onModify(value, key, oldValue) {
		switch (key) {
			case 'dpm':
			case 'dcm':
			case 'dom':
				this['__' + key] = fill(value);
				break;
		}
	}

	mounted() {
		this.host.addEventListener(engine.MouseEvent.CLICK, this._onClick, this);
		//this.host.addEventListener(engine.Event.VISIBLE, this._onVisible, this);

		this._timer = setInterval(this.checkVisibility, 1000 / this.checkFps);
	}

	destroy(): void {
		this.host.removeEventListener(engine.MouseEvent.CLICK, this._onClick, this);
		if (this._timer) {
			clearInterval(this._timer);
			this._timer = null;
		}
	}

	awake(): void {
		if (this.autoExposure && this.autoExposureType === 'awake') {
			this.autoLogExposure();
		}
	}

	private _onVisible(e = null) {
		if (this.autoExposure && this.autoExposureType === 'visible') {
			this.autoLogExposure();
		}
	}

	private checkVisibility = () => {
		let worldVisible = this.host.worldVisible;
		if (worldVisible !== this._hostVisible) {
			this._hostVisible = worldVisible;
			if (worldVisible) {
				this._onVisible();
			}
		}
	};

	private autoLogExposure() {
		if (!this._autoExposured) {
			if (this.onceAutoExposure) {
				this._autoExposured = true;
			}
			this.logExposure();
		}
	}

	private _onClick(e) {
		if (this.autoClick) {
			this.logClick();
		}
	}

	logExposure() {
		this.log('exposure');
	}

	logClick() {
		this.log('click');
	}

	async log(type) {
		let otherQuery:any = {
			appId: engine.env.appID,
		};
		await log(type, {
			dpm: this['__dpm'],
			dcm: this['__dcm'],
			dom: this['__dom'],
		}, otherQuery);
		if (this.id !== undefined) {
			engine.globalEvent.dispatchEvent('buried-point-success', {
				type,
				id: this.id,
			})
		}
	}
}

function fill(src) {
	let result = src;
	for (let key in engine.env) {
		result = result.replace(key, engine.env[key]);
	}
	return result;
}

function log(type, data, otherQuery?: any) {
	let {dpm, dcm, dom} = data;

	const params: any = {
		dpm, dcm,
	};
	if (dom !== '0.0.0.0') {
		params.dom = dom;
	}
	injectProp(params, otherQuery);
	let isExposure = type === 'exposure';

	return engine.httpRequest(
		isExposure ? '//embedlog.duiba.com.cn/exposure/standard' : '/log/click',
		'get',
		params,
		isExposure ? 'jsonp' : 'text'
	);
}
