/**
 * 交易记录逻辑
 */
class Trade {
	private static _instance: Trade;
	static get instance(): Trade {
		if (!this._instance) {
			this._instance = new Trade();
		}
		return this._instance;
	}

	private uiTrade: UI_Trade;
	public tradeList: Array<any> = [];

	public constructor() {
		GameMgr.instance.addEventListener(SocketEvent.PROTO_MSG, this.onRecieved, this);
	}

	onRecieved(ev: SocketEvent) {
		let { protoId, data } = ev;
		if (protoId == Protocol.channelNewOffer) {
			this.renderTradeList([data])
		}
	}

	public renderTradeList(offers: any[]) {
		offers.forEach(item => {
			let trades: any[] = null
			let types = item.offertype.split('|')
			let amounts = item.offeramount.split('|')
			trades = types.map((trade, index) => {
				return {
					account: item.player,
					type: trade * 1,
					total: NP.divide(amounts[index] * 1, 1e4) + ' EOS'
				}

			})
			this.tradeList.push(...trades)
		})

		this.uiTrade && this.uiTrade.renderTradeList();
	}

	public renderGameId(id: string): void {
		this.uiTrade && this.uiTrade.renderGameId(id);
	}

	public emptyTradeList() {
		Trade.instance.tradeList = [];
		this.uiTrade && this.uiTrade.emptyTradeView();
	}

	openTradeView(): void {
		if (this.uiTrade) {
			this.uiTrade.visible = true;
			this.uiTrade.renderTradeList();
		} else {
			this.uiTrade = UIController.instance.popupView<UI_Trade>(UI_Trade);
		}
	}

	closeTradeView(): void {
		if (this.uiTrade) this.uiTrade.visible = false;
	}


	getTradeView(): UI_Trade {
		return this.uiTrade = UIController.instance.createView<UI_Trade>(UI_Trade);
	}
}