import { buildNewSvgImages, buildOtherGenerate, 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, othersGenerate }) => {
  if (!othersGenerate) {
    console.warn('No othersGenerate!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!');
  }
  if (!allCells) {
    console.warn('No allCells!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!');
  }
  console.log('[Western-world] Try to 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;
  }
  console.log('[Western-world] Start fetching images...');
  window['cachedImages'][language].currentPromise = Promise.all([
    buildNewSvgImages({ allCells, language }).then(newSvgImagesResolve[language]),
    Promise.all([buildOtherSvgImages({ language }), buildOtherGenerate({ language, othersGenerate })]).then(
      otherSvgImagesResolve[language]
    )
  ]).then(() => {
    console.log('[Western-world] Images were loaded...');
    return window.cachedImages[language];
  });
  return window['cachedImages'][language].currentPromise;
};

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