import axios from '@/http';
import { parseSvg } from '@meta2d/svg';
import { cdn } from './api';
import { filename } from './file';

export async function getFolders(name: string, isSvg?: boolean) {
  const path = name;
  const folders: any = await axios.post('/api/assets/folders', {
    path,
  });
  if (!folders || !folders.list) {
    return [];
  }

  const files: any = await axios.post('/api/assets/files', {
    path,
  });

  const results = [];
  for (const item of folders.list) {
    let name = item;
    if (folders.prefix) {
      const temp = name.split('/');
      name = temp[temp.length - 2];
    }
    const list = [];
    if (files.list) {
      for (const f of files.list) {
        if (f.indexOf('/'+item+'/') >= 0) {
          const temp = f.split('/');
          const name = filename(temp[temp.length - 1]);
          if (!name) {
            continue;
          }
          const elem: any = {
            name,
            image: cdn + '/' + f,
            isSvg,
          };
          list.push(elem);
        }
      }
    }

    results.push({ name, list });
  }
  return results;
}

export async function makeSvg(elem: any) {
  const svgDom: string = await axios.get(elem.image);
  let _svgDom = svgDom.replaceAll('#333;', '#fff;');
  elem.svg = _svgDom;
  elem.data = parseSvg(_svgDom);
  let le5le = [];
  elem.data.forEach((pen) => {
    if (pen.name === 'svgPath') {
      if (
        pen.path.indexOf('-1.18Zm4-1') !== -1 ||
        pen.path.indexOf('-1.19Zm4-1') !== -1 ||
        pen.path.indexOf('2.85ZM') !== -1 ||
        pen.path.indexOf('-1-2.39.3') !== -1
      ) {
        le5le.push(pen);
      }
    }
  });
  if (le5le.length === 3) {
    le5le.forEach((pen) => {
      (pen as any).svgUrl = elem.image;
    });
  }
}
