'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
const Rx = require('rxjs/Rx');
const fs = require('fs');
const commutable = require('commutable');

const Observable = Rx.Observable;

const writeFileObservable = (filename, data, ...args) => Observable.create(observer => {
  fs.writeFile(filename, data, ...args, error => {
    if (error) {
      observer.error(error);
    } else {
      observer.next({ filename, data });
      observer.complete();
    }
  });
});

const SAVE = exports.SAVE = 'SAVE';
const SAVE_AS = exports.SAVE_AS = 'SAVE_AS';
const CHANGE_FILENAME = exports.CHANGE_FILENAME = 'CHANGE_FILENAME';
const DONE_SAVING = exports.DONE_SAVING = 'DONE_SAVING';

const changeFilename = exports.changeFilename = filename => ({ type: CHANGE_FILENAME, filename });
const save = exports.save = (filename, notebook) => ({ type: SAVE, filename, notebook });
const saveAs = exports.saveAs = (filename, notebook) => ({ type: SAVE_AS, filename, notebook });
const doneSaving = exports.doneSaving = () => ({ type: DONE_SAVING });

const saveEpic = exports.saveEpic = actions => actions.ofType(SAVE).do(action => {
  // If there isn't a filename, save-as it instead
  if (!action.filename) {
    throw new Error('save needs a filename');
  }
}).mergeMap(action => writeFileObservable(action.filename, JSON.stringify(commutable.toJS(action.notebook), null, 1)).map(doneSaving)
// .startWith({ type: START_SAVING })
// since SAVE effectively acts as the same as START_SAVING
// you could just look for that in your reducers instead of START_SAVING
);

const saveAsEpic = exports.saveAsEpic = actions => actions.ofType(SAVE_AS).mergeMap(action => [changeFilename(action.filename), save(action.filename, action.notebook)]);