// 缓存非组件相关信息的
if (!global.__biliCacheData) global.__biliCacheData = {
	font: {                      // 处理字体相关的参数
		openGlobal: false           // 是否开启全局字体
	},
	getCurrentPageId: () => {
	},    // 标准获取pageId方法，保证正确性
	pageIdStatus: '',            // 缓存生命周期变化中pageId的过渡状态
	eventHandler: {				 // 缓存小程序所有需要缓存handler
		keyboard: {
			_cache: {}
		}
	},
	api: {
		keyboard: {
			current: '',
		}
	},
	currentPageId: '',            // 缓存生命周期变化中的pageId（非标准，记录过渡状态，标准请使用 getCurrentPageId 方法）
	// 获取客户端 js bind 提供的统一能力。
	getObjectForNativeCanvas: function (funName) {
		return global.BLGlobal[funName].bind(global.BLGlobal);
	},
	canvas: {
		Image: function (width, height) {
			let _canvasForNA = global.__biliComponentData.canvas.canvasForNA();
			let _image = _canvasForNA.createImage();
			_image.width = width;
			_image.height = height;
			return _image;
		},
		ImageData: function () {
			let _temp = Array.prototype.slice.apply(arguments);
			let _canvasForNA = global.__biliComponentData.canvas.canvasForNA();
			let _offscreenCanvas = _canvasForNA.createCanvas(true, global.__biliCacheData.getCurrentPageId(), 2);
			let _ctx = _offscreenCanvas.getContext('2d');
			return _ctx.createImageData(..._temp);
		}
	},
	eventHandlers: {
		// 截屏回调
		captureListeningHandlers: [],
		// 陀螺仪回调
		gyroscopeChangeHandlers: {},
		// 蓝牙相关回调
		bluetoothChangeHandlers: {
			// 监听搜索到新设备的事件
			onBluetoothDeviceFound: [],
			// 蓝牙适配器状态变化事件
			onBluetoothAdapterStateChange: [],
			// 监听蓝牙低功耗连接状态的改变事件
			onBLEConnectionStateChange: [],
			// 监听蓝牙低功耗设备的特征值变化事件
			onBLECharacteristicValueChange: [],
			// 监听蓝牙低功耗的最大传输单元变化事件（仅安卓触发）
			onBLEMTUChange: [],
			// 监听已连接的设备请求读当前外围设备的特征值事件
			onCharacteristicWriteRequest: [],
			// 特征订阅事件的回调函数
			onCharacteristicReadRequest: [],
			// 特征订阅事件的回调函数
			onCharacteristicSubscribed: [],
			// 监听当前外围设备被连接或断开连接事件
			onBLEPeripheralConnectionStateChanged: [],
			// 取消特征订阅事件的回调函数
			onCharacteristicUnsubscribed: []
		}
	},
	smallAppInfo: {
		appid: APPID
	},
	util: {
		btoa: (() => {
			const KEY_STR = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

			const polyfill = (input) => {
				let output = "";
				let chr1;
				let chr2;
				let chr3;
				let enc1;
				let enc2;
				let enc3;
				let enc4;
				let i = 0;

				while (i < input.length) {

					chr1 = input.charCodeAt(i++);
					chr2 = input.charCodeAt(i++);
					chr3 = input.charCodeAt(i++);

					enc1 = chr1 >> 2;
					enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
					enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
					enc4 = chr3 & 63;

					if (isNaN(chr2)) {
						enc3 = enc4 = 64;
					} else if (isNaN(chr3)) {
						enc4 = 64;
					}

					output = output + KEY_STR.charAt(enc1) + KEY_STR.charAt(enc2) + KEY_STR.charAt(enc3) + KEY_STR.charAt(enc4);

				}

				return output;
			};

			return polyfill;
		})(),
		atob: (() => {
			const KEY_STR = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

			const polyfill = (input) => {
				let output = "";
				let chr1, chr2, chr3;
				let enc1, enc2, enc3, enc4;
				let i = 0;

				input = input.replace(/[^A-Za-z0-9+/=]/g, "");

				while (i < input.length) {

					enc1 = KEY_STR.indexOf(input.charAt(i++));
					enc2 = KEY_STR.indexOf(input.charAt(i++));
					enc3 = KEY_STR.indexOf(input.charAt(i++));
					enc4 = KEY_STR.indexOf(input.charAt(i++));

					chr1 = (enc1 << 2) | (enc2 >> 4);
					chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
					chr3 = ((enc3 & 3) << 6) | enc4;

					output = output + String.fromCharCode(chr1);

					if (enc3 !== 64) {
						output = output + String.fromCharCode(chr2);
					}
					if (enc4 !== 64) {
						output = output + String.fromCharCode(chr3);
					}

				}

				return output;
			};

			return polyfill;
		})(),
		transformArrayBufferToBase64(buffer) {
			let binary = '';
			let bytes = new Uint8Array(buffer);
			for (let len = bytes.byteLength, i = 0; i < len; i++) {
				binary += String.fromCharCode(bytes[i]);
			}

			return global.__biliCacheData.util.btoa(binary);
		},

		urlBase64ToArrayBuffer(base64String) {
			const padding = '='.repeat((4 - base64String.length % 4) % 4);
			const base64 = (base64String + padding)
				.replace(/-/g, '+')
				.replace(/_/g, '/');

			const output = global.__biliCacheData.util.atob(base64);

			const outputArray = new Uint8Array(output.length);

			for (let i = 0; i < output.length; ++i) {
				outputArray[i] = output.charCodeAt(i);
			}

			return outputArray.buffer;
		}
	}
};

// 缓存组件相关信息的
if (!global.__biliComponentData) global.__biliComponentData = {
	canvas: {
		canvasForNA: () => {
		},
		waitingCanvas: [],
		checkoutQuery: () => {
			// console.log('>>> 缓存check...')
			let _temp = global.__biliComponentData.canvas.waitingCanvas;
			let _pageId = global.__biliCacheData.getCurrentPageId();
			let _delIndex = [];
			if (_temp.length > 0) {
				_temp.forEach((_x, i) => {
					let __temp = _x.params.filter(x => x && x['getCanvasInstance']);
					let _isReadyByAll = true;
					if (__temp.length > 0) {
						__temp.forEach(_x => {
							let _readyForCanvas = global.canvas &&
								global.canvas[_pageId] &&
								global.canvas[_pageId][_x["getCanvasInstance"]] &&
								global.canvas[_pageId][_x["getCanvasInstance"]].status === 'ready';
							_isReadyByAll = _isReadyByAll && _readyForCanvas;
						});
					}
					if (_isReadyByAll) {
						_x.params.forEach(_x => {
							if (_x["getCanvasInstance"]) {
								// canvas版本支持
								if (bl.isCanvasSupportedSync()) {
									// console.log('>>> checkout ', _isReadyByAll, global.canvas[_pageId][_x["getCanvasInstance"]].canvas)
									_x['node'] = global.canvas[_pageId][_x["getCanvasInstance"]].canvas;
									// 特殊兼容历史版本...
									global.canvas[_pageId][_x["getCanvasInstance"]].canvas.createImage = global.__biliCacheData.canvas.Image;
									global.canvas[_pageId][_x["getCanvasInstance"]].canvas.createImageData = global.__biliCacheData.canvas.ImageData;
								} else {
									_x['node'] = null;
								}
								// 删除标记
								delete _x["getCanvasInstance"];
							}
						});
						// 调用
						_x.callback(_x.params);
						if (Service.callbacks[_x.callbackId]) delete Service.callbacks[_x.callbackId];
						_x.queueCb.forEach((item, index) => {
							if (item) {
								item(_x.params[index]);
							}
						});
						// 记录删除的索引
						_delIndex.push(i);
					}
				});
			}
			if (_delIndex.length > 0) {
				_delIndex.forEach(y => {
					_temp.splice(y, 1);
				});
			}
		}
	}
};

// 构建相关信息
global.$buildInfo = {
	buildTime: SAPP_BUILDTIME,
	version: SAPP_VERSION,
	smallApp: SAPP_SMALLAPP,
	baseVersion: global._bili_runtime? global._bili_runtime.version : '',
	baseTime: global._bili_runtime? global._bili_runtime.data : ''
}

// 加载字体用的空方法，为安卓老版本兜底使用
Service.executeJSOnPreLoadRender = function () {
	return '';
};

console.log('[biliSapp - build]', global.$buildInfo);
