"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
Object.defineProperty(exports, "__esModule", { value: true });
const core_1 = require("@angular/core");
const http_1 = require("@angular/http");
const effects_1 = require("@ngrx/effects");
const store_1 = require("@ngrx/store");
const lodash_1 = require("lodash");
const Observable_1 = require("rxjs/Observable");
const project_1 = require("./project");
const env_1 = require("../util/env");
const saveWhenChanged = ['code', 'sync'];
/**
 * ngrx effector which saves changes to the state and loads initial
 * data from the history.
 */
let HistoryEffects = class HistoryEffects {
    constructor(http, store, actions) {
        this.http = http;
        this.store = store;
        this.actions = actions;
        this.saveChanges = this.actions
            .delay(1)
            .filter((action) => !action.omitSave)
            .switchMap(() => this.store.take(1).map(project_1.getStoredData))
            .pairwise()
            .filter(([a, b]) => !lodash_1.isEqual(lodash_1.pick(a, saveWhenChanged), lodash_1.pick(b, saveWhenChanged)))
            .debounceTime(3 * 1000)
            .switchMap(([, data]) => this.http.post(env_1.apiUrl('saves'), data));
        this.loadInitialState = this.actions
            .delay(1)
            .take(1)
            .switchMap(() => this.http.get(env_1.apiUrl('saves/latest')))
            .map(res => ({ type: project_1.MetaActions.ReplaceState, data: res.json().contents }))
            .catch(() => Observable_1.Observable.of(null))
            .filter(Boolean);
    }
};
__decorate([
    effects_1.Effect({ dispatch: false }),
    __metadata("design:type", Observable_1.Observable)
], HistoryEffects.prototype, "saveChanges", void 0);
__decorate([
    effects_1.Effect(),
    __metadata("design:type", Object)
], HistoryEffects.prototype, "loadInitialState", void 0);
HistoryEffects = __decorate([
    core_1.Injectable(),
    __metadata("design:paramtypes", [http_1.Http, store_1.Store, effects_1.Actions])
], HistoryEffects);
exports.HistoryEffects = HistoryEffects;
