import {EmitterSubscription, NativeEventEmitter, NativeModules} from 'react-native'
import {
  DeviceInfo,
  NativeProps,
  setGroupDevices,
  setGroupDps,
  setGroupNativeProps,
  setNativeProps,
  UAGroupInfo,
} from '../models/modules/NativePropsSlice'
import {actions} from '@models'
import { cloneDeep } from 'lodash'
import {DpValue} from "tuya-panel-kit";
import {NativeApi} from "./native";

const nativeModule = NativeModules.LDVDeviceEventEmitter

export const nativeEventEmitter = new NativeEventEmitter(nativeModule)

let deviceDPListener: EmitterSubscription | null
let groupFeatureListener: EmitterSubscription | null
let groupDeviceListener: EmitterSubscription | null
let groupDpListener: EmitterSubscription | null

interface GroupFeatureEvent {
  tyGroupId: number
  config: string
  name: string
  icon: string
  deviceIds: string
}

interface GroupDpEvent {
  tyGroupId: number
  dps: any
}

interface DeviceEvent {
  devId: string
  dps: any
  name: string
  pId: string
}

interface TYInfoUpdateType {
  devId: string
  online: boolean
}

export const addListener = (store) => {
  deviceDPListener = nativeEventEmitter.addListener('TYDataUpdate', (event: DeviceEvent) => {
    // device info
    if (event.dps && event.devId && event.devId === store.getState().ldvModules.deviceInfo.devId) {
      console.log('长链接刷新DP数据', event.devId, event.dps)
      // @ts-ignore
      const nativeProps: NativeProps = {
        familyName: '',
        deviceInfo: {
          devId: event.devId,
          pId: event.pId,
          dps: JSON.parse(event.dps),
        },
        uaGroupInfo: {} as UAGroupInfo,
      }
      store.dispatch(setNativeProps(nativeProps))
    }
    // 兼容ios修改设备名称
    if (!!event.name && event.devId && event.devId === store.getState().ldvModules.deviceInfo.devId) {
      store.dispatch(actions.common.devInfoChange({...store.getState().devInfo, name: event.name}))
    }
  })

  groupFeatureListener = nativeEventEmitter.addListener('UAGroupFeatureUpdate', (event: GroupFeatureEvent) => {
    const tyGroupId = Number(event.tyGroupId)
    if (tyGroupId == store.getState().ldvModules.uaGroupInfo.tyGroupId) {
      const newDeviceIds = event.deviceIds ? JSON.parse(event.deviceIds) as string[] : []
      console.log('长链接刷新Group数据', event)
      // @ts-ignore
      const nativeProps: NativeProps = {
        familyName: '',
        deviceInfo: {} as DeviceInfo,
        uaGroupInfo: {
          tyGroupId: tyGroupId,
          pId: '',
          name: event.name,
          icon: event.icon,
          config: JSON.parse(event.config),
          dps: {},
          deviceIds: newDeviceIds,
        } as UAGroupInfo,
      }
      store.dispatch(setGroupNativeProps(nativeProps))
      const oldDeviceIds = store.getState().ldvModules.uaGroupInfo.groupDevices.map(device => device.deviceId);
      const oldDeviceIdsStr = oldDeviceIds.slice().sort().join('');
      const newDeviceIdsStr = newDeviceIds.slice().sort().join('');
      if (oldDeviceIdsStr !== newDeviceIdsStr) {
        NativeApi.getGroupDevices(tyGroupId).then(res => {
          if (res.success && Array.isArray(res.data)) {
            store.dispatch(setGroupDevices(res.data))
          }
        });
      }
    }
  })

  groupDpListener = nativeEventEmitter.addListener('UAGroupDpUpdate', (event: GroupDpEvent) => {
    const tyGroupId = Number(event.tyGroupId);
    const groupId = Number(store.getState().ldvModules.uaGroupInfo.tyGroupId)
    if (tyGroupId === groupId) {
      let data = event.dps
      if (typeof event.dps === 'string') {
        data = JSON.parse(event.dps)
      }
      store.dispatch(setGroupDps(data as Record<string, DpValue>))
    }
  })

  groupDeviceListener = nativeEventEmitter.addListener('TYInfoUpdate', (event: TYInfoUpdateType) =>{
    const groupDevices = cloneDeep(store.getState().ldvModules.uaGroupInfo.groupDevices)
    const idx = groupDevices.findIndex(device => device?.deviceId?.indexOf(event.devId) !== -1)
    if(idx !== -1 && Number(groupDevices[idx].status) !== (event.online ? 1 : 0)){
      groupDevices[idx] = {
        ...groupDevices[idx],
        status: event.online ? 1 : 0
      }
      store.dispatch(setGroupDevices(groupDevices))
    }
  })
}

export const removeListener = () => {
  deviceDPListener && deviceDPListener.remove()
  deviceDPListener = null

  groupFeatureListener && groupFeatureListener.remove()
  groupFeatureListener = null

  groupDeviceListener && groupDeviceListener.remove()
  groupDeviceListener = null

  groupDpListener && groupDpListener.remove()
  groupDpListener = null
}
