import { typeValidator } from "@flare/js-utils";

const setItem = (key, value) => {
  const { isArray, isObject } = typeValidator;
  let valueToStore = value;
  if (isArray(value) || isObject(value)) {
    valueToStore = JSON.stringify(value);
  }

  window.localStorage.setItem(key, valueToStore);
};

const getItem = (key) => {
  var value = window.localStorage.getItem(key);
  const { isJson } = typeValidator;
  var { data, success } = isJson(value);

  if (success) {
    return data;
  } else {
    return value;
  }
};

const removeItem = (key) => {
  window.localStorage.removeItem(key);
};

const clear = () => {
  window.localStorage.clear();
};

const key = (index) => {
  var keyName = window.localStorage.key(index);
  return keyName;
};

export { setItem, getItem, removeItem, clear, key };
