import global from '../common/global';

/**
 * Taf 消息操作封装
 */
export default {
  /**
   * 获取 abab实例
   * @private 
   */
  _getAbab() {
    const { adapter } = global.platform || {};
    const { abab } = adapter || {};
    return abab || global.win;
  },

  /**
   * ArrayBuffer 转 base64
   * @param {ArrayBuffer} ab 要加密的信息
   * @returns {string} 返回加密信息
   */
  encode(ab) {
    let binary = '';
    const bytes = new Uint8Array(ab);
    const len = bytes.byteLength;
    for (let i = 0; i < len; i++) {
      binary += String.fromCharCode(bytes[i]);
    }
    return this._getAbab().btoa(binary);
  },

  /**
   * base64 转 ArrayBuffer 类型
   * @param {string} base64 
   * @returns {ArrayBuffer} 返回解密信息
   */
  decode(base64) {
    const binary = this._getAbab().atob(base64);
    const len = binary.length;
    const bytes = new Uint8Array(len);
    for (let i = 0; i < len; i++) {
      bytes[i] = binary.charCodeAt(i);
    }
    return bytes.buffer;
  },
}
