/* xeslint-disable */
import store from "../store";
import apiUtil from "./apiutil";
import _ from "../utils/libs/lodash.js";

export default {
  get(key) {
    // debugger;
    if (!_.has(store.state.localeText, key)) {
      return "?" + key + "?";
    }
    return store.state.localeText[key];
  },
  fetch(keys) {
    return new Promise(function(resolve, reject) {
      //step 1: build an array of keys that we don't have already
      //Note: this will ensure only unique keys go into the store so it's safe to call this with dupes as can happen
      var needIt = [];
      for (var i = 0; i < keys.length; i++) {
        if (!_.has(store.state.localeText, keys[i])) {
          needIt.push(keys[i]);
        }
      }
      if (needIt.length == 0) {
        resolve();
        return;
      }
      //step 2: get it
      fetch(apiUtil.APIUrl("locale/subset"), apiUtil.fetchPostOptions(needIt))
        .then(apiUtil.status)
        .then(apiUtil.json)
        .then(response => {
          _.forEach(response.data, function(item) {
            store.commit("addLocaleText", item);
          });
          resolve();
        })
        .catch(function(error) {
          reject(error);
        });
    });
  }
};
