import lodash from 'lodash';
import Promise from 'bluebird';

import { browserLocalStorage as storageApi } from './api';

export const storageSet = async (key, value) => {
  return storageApi.set({ [key]: value });
};

export const storageGetAll = async () => {
  const listData = await storageApi.get(null);

  return Object.entries(listData).map(([key, value]) => {
    return { key, value };
  });
};

export const storageGet = async (key) => {
  const get = await storageApi.get(key);

  return lodash.has(get, key) ? get[key] : undefined;
};

export const storageRemove = async (key) => {
  return storageApi.remove(key);
};

export const storageClear = async () => {
  return storageApi.clear();
};

export const storageOnChage = (callback) => {
  storageApi.onChanged.addListener(callback);
};

export const storageSyncFromLocal = async () => {
  const getAll = Object.entries({ ...localStorage });

  return Promise.map(getAll, async ([key, value]) => {
    return storageSet(key, value);
  });
};
