///<reference path="Util.ts" />
class Api {
	public constructor() {
	}
	static url = Util.isDev() ? 'https://test-bptp.eosget.io' : '//baccarat.eosget.io';
	static getNewGameParam: Object = null;
	static generatorDispatchEvent(protoId: number | string, data) {
		let socketEv = new SocketEvent(SocketEvent.PROTO_MSG)
		socketEv.protoId = protoId
		socketEv.data = data
		GameMgr.instance.dispatchEvent(socketEv);
	}
	static httpGet(url, params = {}): Promise<Object> {
		let paramsStr = Object.keys(params).map(key => params[key] && `${key}=${params[key]}`).join('&')
		url += (paramsStr ? `?${paramsStr}` : '')
		return new Promise((resolve, reject) => {
			var request = new egret.HttpRequest();
			request.responseType = egret.HttpResponseType.TEXT;
			request.open(url, egret.HttpMethod.GET);
			request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
			request.send();
			request.addEventListener(egret.Event.COMPLETE, ev => {
				let result = ev.currentTarget
				resolve(JSON.parse(result.response))
			}, this);
			request.addEventListener(egret.IOErrorEvent.IO_ERROR, reject, this);
		})
	}
	static getNewGame(_old: string, _new: string, player?: string) {
		let param = { old: _old, new: _new, player: player }
		this.getNewGameParam = param;
		this.httpGet(`${this.url}/baccarat/gameResult`, param)
			.then((data: any) => {
				if (data.code == 0) {
					if (this.getNewGameParam === param) {
						let _new = data.data.new
						let _old = data.data.old
						let timeout = _new.timeout
						//TODO push rate history
						Rate.instance.pushRateHistory(_old)
						//TODO old game result
						Index.instance.renderLotteryInfo(_old, _new);
					} else {
						console.warn('getNewGame warn:param not lastest', )
					}

				} else {
					console.error('getNewGame error:', data.msg)
				}
			})
	}

	static getGameInfo(game_id?: number) {
		this.httpGet(`${this.url}/baccarat/gameInfo`, { game_id })
			.then((data: any) => {
				if (data.code == 0) {
					let {dig_rate, game, offers, winData, online} = data.data;

					Bet.instance.setRate(dig_rate);
					//TODO render game info
					Index.instance.renderGameInfo(game);

					Index.instance.renderOnlineNumber(online.total);
					//TODO offers
					Trade.instance.renderTradeList(offers);

					offers.forEach(item => Index.instance.renderOfferItem(item));
					//TODO winData
					Rate.instance.renderRateHistory(winData);
				} else {
					console.error('getGameInfo error:', data.msg);
				}
			})
	}
}