import {
  updateAlarmHostApi,
  updateCameraApi,
  updateDecoderApi,
  updateKeyboardApi,
  updateMediaServerApi,
  updateNvrApi,
  updateSecurityBoxApi,
  updateSwitchApi,
  updateVideoServerApi,
  type NdmDeviceResultVO,
  type Station,
} from '@/apis';
import { DEVICE_TYPE_LITERALS, tryGetDeviceType } from '@/enums';

export const updateDeviceApi = async (device: NdmDeviceResultVO, options?: { stationCode?: Station['code']; signal?: AbortSignal }): Promise<NdmDeviceResultVO | undefined> => {
  const { stationCode, signal } = options ?? {};
  const { id, deviceType: deviceTypeCode } = device;
  if (!id || !deviceTypeCode) throw new Error('未知的设备');
  const deviceType = tryGetDeviceType(deviceTypeCode);
  if (!deviceType) throw new Error('未知的设备');
  if (deviceType === DEVICE_TYPE_LITERALS.ndmAlarmHost) {
    await updateAlarmHostApi(device, { stationCode, signal });
    return;
  }
  if (deviceType === DEVICE_TYPE_LITERALS.ndmCamera) {
    await updateCameraApi(device, { stationCode, signal });
    return;
  }
  if (deviceType === DEVICE_TYPE_LITERALS.ndmDecoder) {
    await updateDecoderApi(device, { stationCode, signal });
    return;
  }
  if (deviceType === DEVICE_TYPE_LITERALS.ndmKeyboard) {
    await updateKeyboardApi(device, { stationCode, signal });
    return;
  }
  if (deviceType === DEVICE_TYPE_LITERALS.ndmMediaServer) {
    await updateMediaServerApi(device, { stationCode, signal });
    return;
  }
  if (deviceType === DEVICE_TYPE_LITERALS.ndmNvr) {
    await updateNvrApi(device, { stationCode, signal });
    return;
  }
  if (deviceType === DEVICE_TYPE_LITERALS.ndmSecurityBox) {
    await updateSecurityBoxApi(device, { stationCode, signal });
    return;
  }
  if (deviceType === DEVICE_TYPE_LITERALS.ndmSwitch) {
    await updateSwitchApi(device, { stationCode, signal });
    return;
  }
  if (deviceType === DEVICE_TYPE_LITERALS.ndmVideoServer) {
    await updateVideoServerApi(device, { stationCode, signal });
    return;
  }
  return undefined;
};
