import global from '../common/global';
import base64Util from '../utils/base64';

/**
 * Taf 消息操作封装
 */
export default {
  _Taf: null,

  /**
   * 获取 loadTaf 方法
   * @private 
   */
  async _loadTaf() {
    if (!this._Taf) {
      const { adapter } = global.platform || {}
      const { taf } = adapter || {};
      this._Taf = await taf.loadTaf();
    }
    return this._Taf;
  },

  /**
   * Taf消息 加密
   * @param {object} tafObj TafObj
   * @returns {string} 返回加密信息
   */
  async encode(tafObj = {}) {
    const Taf = await this._loadTaf();
    const os = new Taf.JceOutputStream();
    tafObj.writeTo(os);
    const ab = os.getBinBuffer().getBuffer();
    return base64Util.encode(ab);
  },

  /**
   * Taf消息 解析
   * @param {string} base64Str 要解析的消息
   * @param {Object} parseClazz 解析使用的Class
   * @returns {any} 机密信息
   */
  async decode(base64Str, parseClazz) {
    const Taf = await this._loadTaf();
    const ab = base64Util.decode(base64Str);
    const is = new Taf.JceInputStream();
    is.buf = new Taf.BinBuffer(ab);
    const rsp = new parseClazz();
    rsp.readFrom(is);
    return rsp;
  },
}
