/**
 * Created by rockyl on 2018-12-16.
 *
 * Api接口组件基类
 */

import {engine, ScillaEvent} from "scilla";
import ScillaComponent from "components/base/ScillaComponent";

export enum RequestMethod{
	GET = 'GET',
	POST = 'POST',
	PUT = 'PUT',
	DELETE = 'DELETE',
}

export default class ApiComponent extends ScillaComponent {
	name: string;
	method: RequestMethod = RequestMethod.POST;
	params: any;

	onResponse: ScillaEvent = new ScillaEvent();
	onError: ScillaEvent = new ScillaEvent();
	onFinish: ScillaEvent = new ScillaEvent();

	autoCall: boolean = false;

	private _args;

	onAwake() {
		super.onAwake();

		if(this.autoCall){
			this.execute();
		}
	}

	protected async execute(paramsInput?, ...args) {
		this._args = args;
	}

	onGotResponse(response: any) {
		if(this.name){
			engine.dataCenter.set('API', this.name, response.data);
		}

		if(this._args && this._args.length > 0){
			this.onResponse.invoke(response.data, ...this._args);
		}else{
			this.onResponse.invoke(response.data);
		}
		this.onCallFinish();
	}

	onGotError(e) {
		if(this._args && this._args.length > 0){
			this.onError.invoke(e, ...this._args);
		}else{
			this.onError.invoke(e);
		}
		this.onCallFinish();
	}

	onCallFinish(){
		if(this._args && this._args.length > 0){
			this.onFinish.invoke(...this._args);
		}else{
			this.onFinish.invoke();
		}
	}
}
