import { reactive } from 'vue';

const ImageMap = reactive({});
const allImages = import.meta.glob(`/src/assets/{images,dark}/**/*.{png,jpg,svg,gif,webp}`);

const findSrc = (path, defaultPath) => {
  if (!defaultPath.includes('/')) {
    let [start, end] = path?.split('.') ?? [];
    start = start?.split('/') ?? [];
    start.pop();
    defaultPath = `${start.join('/')}/${defaultPath}.${end}`;
  } else if (path.includes('/dark/')) {
    defaultPath = defaultPath.replace('/images/', '/dark/');
  }
  // console.log('~~~~~~~~~~~ path', path);
  const targetPath = allImages[path] ? path : defaultPath;

  if (allImages[targetPath]) {
    if (!ImageMap[targetPath]) {
      ImageMap[targetPath] = '';
      allImages[targetPath]()
        .then((result) => {
          ImageMap[targetPath] = result.default;
        });
    }
  } else {
    return null;
  }
  // if (!ImageMap[targetPath]) {
  //   ImageMap[targetPath] = '';
  //
  //   if (allImages[path]) {
  //     allImages[path]()
  //       .then((result) => {
  //         ImageMap[path] = result.default;
  //       });
  //   } else if (allImages[defaultPath]) {
  //     console.log('defaultPath', defaultPath);
  //     allImages[defaultPath]()
  //       .then((result) => {
  //         ImageMap[path] = result.default;
  //       });
  //   }
  // }

  return ImageMap[path] || ImageMap[defaultPath];
};

export const $getSrc = ($store, path, defaultPath = '') => {
  const { darkTheme } = $store.state.app;
  if (darkTheme === 'dark') {
    const target = findSrc(path.replace('/images/', '/dark/'), defaultPath);
    if (target !== null) return target;
  }
  return findSrc(path, defaultPath);
};
