import Bridge from '../manager/BridgeManager'
import { BridgeParams } from '../types/type'
import bus from '../shared/bus'

var persistentCallbackId: string[] = [];

function isBrowser(): boolean {
  if (typeof window != 'undefined') {
    return true;
  }
  return false;
}

function processNativeCallBack(str: string) {
  console.log(str);
  try {
    let body = JSON.parse(str);
    let { methodId, response } = body;
    // 如果 response 内部还包装了一层，需要读取内层
    let res = response?.data || response
    if (!res) {
      res = {
        data: {}
      };
    }
    // 如果res.data是json字符串则转换为对象
    if (res.data && (typeof res.data === 'string')) {
      try {
        res.data = JSON.parse(res.data)
      } catch (e) { }
    }
    // 如果bus中没有methodId
    if (!bus.has(methodId)) {
      return;
    }
    //
    bus.fire(methodId, response);
    // 判断，如果不是持久的回调函数，则调用完毕之后删除该回调
    let index = persistentCallbackId.indexOf(methodId)
    if (index < 0) {
      bus.remove(methodId)
    }
    console.log('end processNativeCallBack');
  }
  catch(e) {
    //
  }
  /**
  //UtilManager.log('Response=' + JSON.stringify(params));
    BridgeManager.response(methodId, res)
   */
}

function callNative(bridgeParams: BridgeParams): Promise<any> {
  if (isBrowser()) {
    return new Promise((resolve) => {
      let methodId = bus.register((res) => {
        resolve(res);
      })
      let data = {
        methodId, 
        request: bridgeParams
      } 
      let g: any = window as any;
      g?.coolinkMpWeb.mpCall(JSON.stringify(data));
    });
  } else {
    return Bridge.invoke(bridgeParams);
  }
}

function callNativeWithPersistentCallBack(bridgeParams: BridgeParams, methodId: string, callback: Function): void {
  if (isBrowser()) {
    // 先检测 persistentCallbackId 中是否已经有 methodId
    let index = persistentCallbackId.indexOf(methodId);
    if (index < 0) {
      persistentCallbackId.push(methodId);
    }
    // 
    bus.remove(methodId);
    if (callback && (typeof callback == 'function')) {
      bus.register(callback, methodId);
    }
    //
    let data = {
      methodId, 
      request: bridgeParams
    } 
    let g: any = window as any;
    g?.coolinkMpWeb.mpCall(JSON.stringify(data));
  } else {
    Bridge.invokeWithPersistentCallBack(bridgeParams, methodId, callback);
  }
}

export default {
  callNative,
  isBrowser,
  processNativeCallBack,
  callNativeWithPersistentCallBack
}



