import axios from "@/http";
import { parseSvg } from "@meta2d/svg";
import { cdn } from "./api";
import { getFolders } from "./png";
const market = import.meta.env.VITE_MARKET;

const normalFolder = market ? "/2d/svg/" : "/svg/";
/**
 * 请求 svg 的目录
 * @returns
 */
export async function getIconFolders() {
  return await getFolders(normalFolder);
}
/**
 * 请求 svg 目录下的所有 svg
 * @param name 目录名
 * @returns
 */
export async function getIcons(name: string) {
  const files = (await axios.get(normalFolder + name + "/")) as any[];
  return await Promise.all(files.map((f) => svgToPens(f, name)));
}

export function filename(str: string) {
  const i = str.lastIndexOf(".");
  return str.substring(0, i);
}

async function svgToPens(f: any, diretoryName: string) {
  const _name = filename(f.name);
  const name = globalThis.fileJson
    ? globalThis.fileJson[_name]
      ? globalThis.fileJson[_name]
      : _name
    : _name;
  const image = cdn + normalFolder + diretoryName + "/" + f.name;
  const svgDom: string = await axios.get(image);
  let _svgDom = svgDom.replace("stroke:#333;", "stroke:#bdc7db;");
  const data = parseSvg(_svgDom);
  return {
    name,
    pinyin: globalThis.fileJson ? _name : null,
    // image, // image 只作为缩略图
    componentDatas: data,
    svg: _svgDom,
    component: true,
  };
}
