import { MessageItem } from "@openim/wasm-client-sdk";
import { v4 as uuidV4 } from "uuid";

import { IMSDK } from "@/layout/MainContentWrap";
import { uploadFile } from "@/utils/imCommon";

export interface FileWithPath extends File {
  path?: string;
}

const getPicInfo = (file: File): Promise<HTMLImageElement> =>
  new Promise((resolve, reject) => {
    const _URL = window.URL || window.webkitURL;
    const img = new Image();
    img.onload = function () {
      resolve(img);
    };
    img.onerror = reject;
    img.src = _URL.createObjectURL(file);
  });

export function useFileMessage() {
  const getImageMessage = async (file: FileWithPath): Promise<MessageItem> => {
    if (window.electronAPI && file.path) {
      const imageMessage = (await IMSDK.createImageMessageFromFullPath(file.path))
        .data as MessageItem;
      imageMessage.pictureElem!.sourcePicture.url = URL.createObjectURL(file);
      return imageMessage;
    }

    const { width, height } = await getPicInfo(file);
    const {
      data: { url },
    } = await uploadFile(file);
    const baseInfo = {
      uuid: uuidV4(),
      type: file.type,
      size: file.size,
      width,
      height,
      url: URL.createObjectURL(file),
    };
    const imageMessage = (
      await IMSDK.createImageMessageByURL({
        sourcePicture: { ...baseInfo, url },
        bigPicture: { ...baseInfo, url },
        snapshotPicture: { ...baseInfo, url },
        sourcePath: "",
      })
    ).data as MessageItem;
    // 本地预览用 blob 地址，避免发送中图片空白
    imageMessage.pictureElem!.snapshotPicture!.url = baseInfo.url;
    return imageMessage;
  };

  const getFileMessage = async (file: FileWithPath): Promise<MessageItem> => {
    if (window.electronAPI && file.path) {
      return (await IMSDK.createFileMessageFromFullPath(file.path, file.name))
        .data as MessageItem;
    }
    const {
      data: { url },
    } = await uploadFile(file);
    return (
      await IMSDK.createFileMessageByURL({
        filePath: "",
        fileName: file.name,
        uuid: uuidV4(),
        sourceUrl: url,
        fileSize: file.size,
        fileType: file.type,
      })
    ).data as MessageItem;
  };

  const getSoundMessage = async (
    file: FileWithPath,
    duration: number,
  ): Promise<MessageItem> => {
    if (window.electronAPI) {
      const filePath = file.path ?? (await window.electronAPI.saveFileToDisk({ file, sync: true }));
      return (await IMSDK.createSoundMessageFromFullPath(filePath, duration))
        .data as MessageItem;
    }
    const {
      data: { url },
    } = await uploadFile(file);
    return (
      await IMSDK.createSoundMessageByURL({
        uuid: uuidV4(),
        soundPath: "",
        sourceUrl: url,
        dataSize: file.size,
        duration,
        soundType: file.type,
      })
    ).data as MessageItem;
  };

  return {
    getImageMessage,
    getFileMessage,
    getSoundMessage,
  };
}
