import type { RobotGroup } from '@api/robot';
import http from '@core/http';
import ws from '@core/ws';

import type { GroupSceneDetail, SceneDetail, SceneInfo } from './type';

const enum API {
  获取场景 = '/scene/getById',
  保存场景 = '/scene/saveById',
  推送场景 = '/scene/pushById',

  获取组场景 = '/scene/getByGroupId',
  保存组场景 = '/scene/saveByGroupId',

  实时监控场景 = '/scene/monitor/:id',
}

export async function getSceneById(id: SceneInfo['id']): Promise<SceneDetail | null> {
  if (!id) return null;
  type B = { id: string };
  type D = SceneDetail;
  try {
    const body = { id };
    const data = await http.post<D, B>(API.获取场景, body);
    return data ?? null;
  } catch (error) {
    console.debug(error);
    return null;
  }
}

export async function saveSceneById(id: SceneInfo['id'], json: string, png?: string): Promise<boolean> {
  if (!id) return false;
  type B = { id: string; json: string; png?: string };
  type D = void;
  try {
    const body = { id, json, png };
    await http.post<D, B>(API.保存场景, body);
    return true;
  } catch (error) {
    console.debug(error);
    return false;
  }
}

export async function pushSceneById(id: SceneInfo['id']): Promise<boolean> {
  if (!id) return false;
  type B = { id: string };
  type D = void;
  try {
    const body = { id };
    await http.post<D, B>(API.推送场景, body);
    return true;
  } catch (error) {
    console.debug(error);
    return false;
  }
}

export async function getSceneByGroupId(
  id: RobotGroup['id'],
  sid: RobotGroup['sid'],
): Promise<GroupSceneDetail | null> {
  if (!id || !sid) return null;
  type B = { id: string; sid: string };
  type D = GroupSceneDetail;
  try {
    const body = { id, sid };
    const data = await http.post<D, B>(API.获取组场景, body);
    return data ?? null;
  } catch (error) {
    console.debug(error);
    return null;
  }
}

export async function saveSceneByGroupId(id: RobotGroup['id'], sid: RobotGroup['sid'], json: string): Promise<boolean> {
  if (!id || !sid) return false;
  type B = { id: string; sid: string; json: string };
  type D = void;
  try {
    const body = { id, sid, json };
    await http.post<D, B>(API.保存组场景, body);
    return true;
  } catch (error) {
    console.debug(error);
    return false;
  }
}

export async function monitorSceneById(id: SceneInfo['id']): Promise<WebSocket | null> {
  if (!id) return null;
  try {
    const socket = await ws.create(API.实时监控场景.replace(':id', id));
    return socket;
  } catch (error) {
    console.debug(error);
    return null;
  }
}
