import {API, DashboardFactory, LocalStorage} from '@bthlabs/homehub-core';
import debounce from 'lodash/debounce';

let offlineMode = false;

export const setOfflineMode = (newOfflineMode) => {
  offlineMode = newOfflineMode;
};

const delay = () => {
  return new Promise((resolve) => {
    window.setTimeout(resolve, 1000);
  });
};

export const loadState = async () => {
  let result = null;
  if (!offlineMode) {
    result = await API.State.get();
  } else {
    const stateJSON = LocalStorage.getItem('state');
    let state = {
      dashboards: [],
    };

    if (stateJSON !== null) {
      state = JSON.parse(stateJSON);
    } else {
      state.dashboards.push(DashboardFactory());
    }

    result = {
      data: state,
    };
  }

  await delay(); // Hehehe

  if (result.error) {
    throw result.error;
  }

  return result.data;
};

export const doSaveState = async (state) => {
  let result = null;
  if (!offlineMode) {
    result = await API.State.save(state);
  } else {
    LocalStorage.setItem('state', JSON.stringify(state));

    result = {
      data: true,
    };
  }

  if (result.error) {
    throw result.error;
  }

  return result.data;
};

export const saveState = debounce(doSaveState, 50);
