import * as WxOpenSdk from '@tencent/wechat_open_sdk';
import { Constants } from '../../common/Constants';

export const WXApi = WxOpenSdk.WXAPIFactory.createWXAPI(Constants.WX_APP_ID)

export type OnWXReq = (req: WxOpenSdk.BaseReq) => void
export type OnWXResp = (resp: WxOpenSdk.BaseResp) => void

// WXApiEventHandler为微信数据的回调
class WXApiEventHandlerImpl implements WxOpenSdk.WXApiEventHandler {
  private TAG = 'WXApiEventHandlerImpl';

  private onReqCallbacks: Map<OnWXReq, OnWXReq> = new Map
  private onRespCallbacks: Map<OnWXResp, OnWXResp> = new Map

  registerOnWXReqCallback(on: OnWXReq) {
    this.onReqCallbacks.set(on, on)
  }
  unregisterOnWXReqCallback(on: OnWXReq) {
    this.onReqCallbacks.delete(on)
  }

  registerOnWXRespCallback(on: OnWXResp) {
    this.onRespCallbacks.set(on, on)
  }
  unregisterOnWXRespCallback(on: OnWXResp) {
    this.onRespCallbacks.delete(on)
  }

  onReq(req: WxOpenSdk.BaseReq): void {
    console.log(this.TAG, "onReq:%s", JSON.stringify(req))
    this.onReqCallbacks.forEach((on) => {
      on(req)
    })
  }

  onResp(resp: WxOpenSdk.BaseResp): void {
    console.log(this.TAG, "onResp:%s", JSON.stringify(resp))
    this.onRespCallbacks.forEach((on) => {
      on(resp)
    })
  }
}

export const WXEventHandler = new WXApiEventHandlerImpl