import { Mutex } from 'async-mutex';

const mutex = new Mutex();


class CategoryService {
  constructor() {
    this.get = this.get.bind(this);
  }

  getSync(categoryId, language = "de") {
    const cacheKey = `${categoryId}_${language}`;
    if (window.categoryCache && window.categoryCache[cacheKey]) {
      return window.categoryCache[cacheKey];
    }
    return null;
  }
  
  async get(categoryId, language = "de") {

   return await mutex.runExclusive(async () => {
      console.log("mutex locked");


      const cacheKey = `${categoryId}_${language}`;
      if (window.categoryCache && window.categoryCache[cacheKey]) {
        console.log("mutex unlocked and returning cached value");
        return Promise.resolve(window.categoryCache[cacheKey]);
      }
      
      return new Promise((resolve) => {
        window.socketManager.emit("categoryList", {categoryId: categoryId, language: language, requestTranslation: language === "de" ? false : true}, (response) => {
          console.log("CategoryService", cacheKey);
          if (response.translatedCategoryTree) {
            if (!window.categoryCache) {
              window.categoryCache = {};
            }
            window.categoryCache[cacheKey] = response.translatedCategoryTree;
            console.log("mutex unlocked and returning new value");
            resolve(response.translatedCategoryTree);
          } else if (response.categoryTree) {
            if (!window.categoryCache) {
              window.categoryCache = {};
            }
            window.categoryCache[cacheKey] = response.categoryTree;
            console.log("mutex unlocked and returning new value");
            resolve(response.categoryTree);
          } else {
            console.log("mutex unlocked and returning null");
            resolve(null);
          }
        });
      });

    });

  }
}

const categoryService = new CategoryService();
window.categoryService = categoryService;

export default categoryService; 