

import { EmitterSubscription, NativeEventEmitter, NativeModules, Platform } from 'react-native';

const pushModule = NativeModules.UmPush
const pushEmitter = new NativeEventEmitter(pushModule);

let foregroundNotification: EmitterSubscription | null = null;
let backstageNotification: EmitterSubscription | null = null;


/**
*  普通注册通知 
*   android需要再工程中注册
*/
const plainRegister = () => {
    if (Platform.OS == 'ios') {
        return pushModule.plainRegister() as Promise<Boolean>
    } else {
        return Promise.resolve(true)
    }
}

/**
 *  快捷交互 注册通知
 * android要在工程中注册
 * @param categories 注册事件数据
 * 
 */
const actionRegister = (categories: { categoryId: string, actions: { actionId: string, actionTitle: string }[] }[]) => {
    if (Platform.OS == 'ios') {
        return pushModule.actionRegister(categories) as Promise<Boolean>
    } else {
        return Promise.resolve(true)
    }
}

/**
 *  设置是否允许SDK当应用在前台运行收到Push时弹出Alert框（默认开启）
 * @param value 是否开启弹出框
 */
const setAutoAlert = (value: boolean) => {
    pushModule.setAutoAlert(value)
}

/**
 *  监听 后台点击通知推送
 */
const addBackstageNotificationListener = (listener: (userInfo: object) => void) => {
    backstageNotification?.remove()
    backstageNotification = pushEmitter.addListener('backstageNotification', listener)
}

/**
 *  监听 前台点击通知推送
 */
const addForegroundNotificationListener = (listener: (userInfo: object) => void) => {
    foregroundNotification?.remove()
    foregroundNotification = pushEmitter.addListener('foregroundNotification', listener)
}

/**
*  普通注册通知
*/
const getTags = () => {
    return pushModule.getTags() as Promise<string[]>
}


/**
*  添加标签
*  @param tag 便签字符串
*/
const addTags = (tag: string) => {
    return pushModule.addTags(tag) as Promise<any>
}


/**
* 移除标签
* @param tag 便签字符串
*/
const deleteTags = (tag: string) => {
    return pushModule.deleteTags(tag) as Promise<any>
}


export default { plainRegister, actionRegister, setAutoAlert, getTags, addTags, deleteTags, addForegroundNotificationListener, addBackstageNotificationListener }