'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.extendReducer = exports.store = undefined;

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _redux = require('redux');

var _reduxThunk = require('redux-thunk');

var _reduxThunk2 = _interopRequireDefault(_reduxThunk);

var _reduxObservers = require('redux-observers');

var _lodash = require('lodash');

var _electron = require('electron');

var _promiseAction = require('./middlewares/promise-action');

var _redux2 = require('./redux');

var _quests = require('./redux/info/quests');

var _battle = require('./redux/battle');

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

const cachePosition = '_storeCache';
const targetPaths = ['const', 'info', 'fcd'];
const storeCache = function () {
  try {
    // clears store when in safe mode
    const item = !window.isSafeMode ? localStorage.getItem(cachePosition) : '{}';
    return JSON.parse(item || '{}');
  } catch (e) {
    return {};
  }
}

//### Utils ###

();const setLocalStorage = () => {
  if (!window.isMain) {
    return;
  }
  process.nextTick(() => {
    localStorage.setItem(cachePosition, JSON.stringify(storeCache));
  });
};

const setLocalStorageDebounced = (0, _lodash.debounce)(setLocalStorage, 5000);

function autoCacheObserver(store, path) {
  return (0, _reduxObservers.observer)(state => (0, _lodash.get)(state, path), (dispatch, current, previous) => {
    (0, _lodash.set)(storeCache, path, current);
    setLocalStorageDebounced();
  });
}

_electron.remote.getCurrentWindow().on('close', e => {
  if (window.isMain) {
    localStorage.setItem(cachePosition, JSON.stringify(storeCache));
  }
}

//### Executing code ###

);const store = exports.store = window.dbg && window.dbg.isEnabled() ? (0, _redux.createStore)((0, _redux2.reducerFactory)(), storeCache, (0, _redux.compose)((0, _redux.applyMiddleware)(_promiseAction.middleware, _reduxThunk2.default), window.devToolsExtension ? window.devToolsExtension() : f => f)) : (0, _redux.createStore)((0, _redux2.reducerFactory)(), storeCache, (0, _redux.compose)((0, _redux.applyMiddleware)(_promiseAction.middleware, _reduxThunk2.default)));
window.dispatch = store.dispatch;

//### Listeners and exports ###

window.getStore = path => {
  return path ? (0, _lodash.get)(store.getState(), path) : store.getState();
};

// Listen to config.set event
const solveConfSet = (path, value) => {
  const details = {
    path: path,
    value: JSON.parse(JSON.stringify(value))
  };
  store.dispatch((0, _redux2.onConfigChange)(details));
};
const config = _electron.remote.require('./lib/config');
config.addListener('config.set', solveConfSet);
window.addEventListener('unload', e => {
  config.removeListener('config.set', solveConfSet);
}

// When any targetPath is modified, store it into localStorage
);if (window.isMain) (0, _reduxObservers.observe)(store, targetPaths.map(path => autoCacheObserver(store, path))

// Save quest tracking to the file when it changes
);if (window.isMain) (0, _reduxObservers.observe)(store, [(0, _reduxObservers.observer)(state => state.info.quests.records, (dispatch, current, previous) => (0, _quests.saveQuestTracking)(current))]);

(0, _quests.schedualDailyRefresh)(store.dispatch

// Dispatch an action '@@BattleResult' when a battle is completed
);(0, _reduxObservers.observe)(store, [(0, _reduxObservers.observer)(state => state.battle.result, _battle.dispatchBattleResult)]

// Use this function to extend extra reducers to the store, such as plugin
// specific data maintainance.
// Use extensionSelectorFactory(key) inside utils/selectors to access it.
);const extendReducer = exports.extendReducer = function () {
  let _reducerExtensions = {};

  return function (key, reducer) {
    const _reducerExtensionsNew = _extends({}, _reducerExtensions, {
      [key]: reducer
    });
    try {
      store.replaceReducer((0, _redux2.reducerFactory)(_reducerExtensionsNew));
      _reducerExtensions = _reducerExtensionsNew;
    } catch (e) {
      console.warn(`Reducer extension ${key} is not a valid reducer`, e.stack);
    }
  };
}();

window.config.get = (path, value) => {
  return (0, _lodash.get)(window.getStore('config'), path, value);
};