import { buildNewSvgImages, buildOtherSvgImages } from './western-world-build-svg.helpers';

// resolvers;
let newSvgImagesResolve = {
  en: null,
  ru: null,
  uk: null,
};

// resolvers;
// let newSvgImagesWithoutMasksResolve = {
//   en: null,
//   ru: null,
//   uk: null,
// };

let otherSvgImagesResolve = {
  en: null,
  ru: null,
  uk: null,
};

window['cachedImages'] = {
  en: {
    svgTags: {},
    svgImagesForCanvas: {},
    svgImagesWithoutMasks: {},
    avatarsMapForCanvas: {},
    currentPromise: null,
    resolver: {
      all: Promise.all([
        new Promise((resolve) => (newSvgImagesResolve['en'] = resolve)),
        new Promise((resolve) => (otherSvgImagesResolve['en'] = resolve)),
      ]),
    },
  },
  ru: {
    svgTags: {},
    svgImagesForCanvas: {},
    svgImagesWithoutMasks: {},
    avatarsMapForCanvas: {},
    currentPromise: null,
    resolver: {
      all: Promise.all([
        new Promise((resolve) => (newSvgImagesResolve['ru'] = resolve)),
        new Promise((resolve) => (otherSvgImagesResolve['ru'] = resolve)),
      ]),
    },
  },
  uk: {
    svgTags: {},
    svgImagesForCanvas: {},
    svgImagesWithoutMasks: {},
    avatarsMapForCanvas: {},
    currentPromise: null,
    resolver: {
      all: Promise.all([
        new Promise((resolve) => (newSvgImagesResolve['uk'] = resolve)),
        new Promise((resolve) => (otherSvgImagesResolve['uk'] = resolve)),
      ]),
    },
  },
};

// TODO split to different functions;
const fetchImages = ({ language, allCells }) => {
  console.log('fetch images...');
  if (
    Object.keys(window['cachedImages'][language].svgTags).length &&
    Object.keys(window['cachedImages'][language].svgImagesForCanvas).length &&
    Object.keys(window['cachedImages'][language].svgImagesWithoutMasks).length
  ) {
    return Promise.resolve(window['cachedImages'][language]);
  }
  if (window['cachedImages'][language].currentPromise) {
    return window['cachedImages'][language].currentPromise;
  }
  window['cachedImages'][language].currentPromise = Promise.all([
    buildNewSvgImages({ allCells, language }).then(newSvgImagesResolve[language]),
    buildOtherSvgImages({ language }).then(otherSvgImagesResolve[language]),
  ]).then(() => window.cachedImages[language]);
  return window['cachedImages'][language].currentPromise;
};

window['western-world-utils'] = {
  fetchImages,
};
