'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.setThemeEpic = exports.getStoredThemeEpic = exports.setTheme = exports.setStoredThemeObservable = exports.getStoredThemeObservable = undefined;

var _electronJsonStorage = require('electron-json-storage');

var _electronJsonStorage2 = _interopRequireDefault(_electronJsonStorage);

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

const Rx = require('rxjs/Rx');

const Observable = Rx.Observable;

const constants = require('../constants');

const getStoredThemeObservable = exports.getStoredThemeObservable = () => Observable.create(observer => {
  _electronJsonStorage2.default.get('theme', (error, data) => {
    if (error) {
      observer.error(error);
    } else if (Object.keys(data).length === 0) {
      observer.complete();
    } else {
      observer.next(data.theme);
    }
    observer.complete();
  });
});

const setStoredThemeObservable = exports.setStoredThemeObservable = theme => Observable.create(observer => {
  _electronJsonStorage2.default.set('theme', { theme }, error => {
    if (error) {
      observer.error(error);
    }
    observer.complete();
  });
});

const setTheme = exports.setTheme = theme => ({
  type: constants.SET_THEME,
  theme
});

const getStoredThemeEpic = exports.getStoredThemeEpic = () =>
// Basically a one-shot
// Leaving this with the redux observable setup because
// * This is our main asynchronous dispatch
// * We could turn this into watching the theming file continuously
getStoredThemeObservable().map(setTheme);

// storage.set('theme', { theme });

const setThemeEpic = exports.setThemeEpic = action$ => action$.ofType(constants.SET_THEME).mergeMap(action => setStoredThemeObservable(action.theme));