/**
 * Created by hwj on 2018/12/1.
 *
 * 简单的api组件
 */

import {raw, utils,} from 'scilla'
import ApiComponent from "./ApiComponent";
import { polling} from "../net/webService";

export default class SamplePollingApi extends ApiComponent {
	successField: string;
	successValues: raw;
	uri: string;
	maxTimes = 5;
	delay = 500;

	private _abortFlag = false;

	async callApi(name, paramsInput, ...args) {
		if (this.name == name) {
			await this.execute(paramsInput, ...args);
		}
	}

	abortCallApi(name){
		if (this.name == name) {
			this._abort();
		}
	}

	protected async execute(paramsInput?, ...args) {
		await super.execute(paramsInput, ...args);

		this._abortFlag = false;

		const params = {};

		if (this.params) {
			utils.injectProp(params, this.params);
		}

		if (paramsInput) {
			utils.injectProp(params, paramsInput);
		}

		const {uri, method} = this;

		try {
			const response = await polling(this.successFunc, uri, params, this.maxTimes, this.delay, this.abortFunc, method);

			this.onGotResponse(response);

			return response.data;
		} catch (e) {
			this.onGotError(e);
		}
	}

	protected abortFunc=()=>{
		return this._abortFlag;
	}

	protected _abort(){
		this._abortFlag = true;
	}

	successFunc=(response)=> {
		const {successField, successValues} = this;
		let v = successField ? response.data[successField] : response.data;
		return successValues ? successValues.indexOf(v) >= 0 : false;
	}
}
