/**
 * 半屏小程序相关接口
 */
import {callNative} from './util';
import * as eventHandlers from './util/eventHandlers';
import shortId from 'shortid';

const {systemHandlers} = eventHandlers;

export default {
	/**
	 * 获取当前APP模式（夜间模式，正常模式）
	 * */
	onColorSchemeChange(callback = () => {
	}) {
		systemHandlers.onWidgetThemeChange.push(callback);
	},
	/**
	 * 获取设备屏幕旋转方向。
	 * */
	onOrientationChange(callback = () => {
	}) {
		eventHandlers.deviceHandlers.orientationChange.push(callback);
	},
	/**
	 * 半屏小程序键盘使用
	 * */
	showKeyboard(options = {
		defaultValue: '',
		multiple: false,
		confirmHold: false,
		maxLength: -1,
		confirmType: 'done',
		hasButton: true,
		customButtons: [],
		keyboardInput: () => {},
		keyboardConfirm: () => {},
		keyboardComplete: () => {},
		keyboardCustomButtonTap: () => {},
		success: () => {},
		fail: () => {},
		complete: () => {},
	}) {
		let _shortId = shortId.generate();
		// 标记全局当前键盘归属
		global.__biliCacheData.api.keyboard.current = _shortId;
		// 特殊处理 keyboardComplete
		let _keyboardComplete = function (data) {
			// 键盘关闭后，清除
			if (global.__biliCacheData.eventHandler.keyboard._cache[_shortId]) {
				delete global.__biliCacheData.eventHandler.keyboard._cache[_shortId];
			}
			global.__biliCacheData.api.keyboard.current = '';
			if (typeof options.keyboardComplete === "function") options.keyboardComplete(data);
		};

		// 缓存键盘id相关的回调函数
		global.__biliCacheData.eventHandler.keyboard._cache[_shortId] = {
			onKeyboardInput: options.keyboardInput,
			onKeyboardConfirm: options.keyboardConfirm,
			onKeyboardComplete: _keyboardComplete,
			onKeyboardCustomButtonTap: options.keyboardCustomButtonTap,
		};

		callNative('showKeyboard', Object.assign(options, {
			hasBlur: true
		}));
	},
	/**
	 * 隐藏键盘，并删除全局键盘缓存
	 * */
	hideKeyboard(options = {}) {
		callNative('hideKeyboard', options);
	},
	/**
	 * 更新键盘value值
	 * */
	updateKeyboard(options = {}) {
		callNative('updateKeyboard', options);
	},
	/**
	 * 监听系统主题改变事件。该事件与 App.onThemeChange 的回调时机一致。
	 * */
	onThemeChange(callback) {
		if (typeof callback !== 'function') {
			throw new Error('参数须是一个函数');
		}
		eventHandlers.systemHandlers.onThemeChange.push(callback);
	},
	/**
	 * 取消监听系统主题改变事件
	 * */
	offThemeChange(callback) {
		if (typeof callback !== 'function') {
			eventHandlers.systemHandlers.onThemeChange.splice(0, eventHandlers.systemHandlers.onThemeChange.length);
		} else {
			const index = eventHandlers.systemHandlers.onThemeChange.indexOf(callback);
			if (index >= 0) {
				eventHandlers.systemHandlers.onThemeChange.splice(index, 1);
			}
		}

	}
};
