import { Observable } from 'rxjs/Rx';
import { Http } from '@angular/http';
import { Injectable } from '@angular/core';
import { ApiRoot } from 'dotcms-js/dotcms-js';
import { ConditionGroupModel } from './Rule';
import { HttpCode } from 'dotcms-js/dotcms-js';
import { LoggerService } from 'dotcms-js/dotcms-js';
var ConditionGroupService = (function () {
    function ConditionGroupService(apiRoot, http, loggerService) {
        this.loggerService = loggerService;
        this._typeName = 'Condition Group';
        this._apiRoot = apiRoot;
        this._http = http;
        this._baseUrl = apiRoot.baseUrl + 'api/v1/sites/' + apiRoot.siteId + '/ruleengine/rules';
    }
    ConditionGroupService.toJson = function (conditionGroup) {
        var json = {};
        json.id = conditionGroup.key;
        json.operator = conditionGroup.operator;
        json.priority = conditionGroup.priority;
        json.conditions = conditionGroup.conditions;
        return json;
    };
    ConditionGroupService.toJsonList = function (models) {
        var list = {};
        Object.keys(models).forEach(function (key) {
            list[key] = ConditionGroupService.toJson(models[key]);
        });
        return list;
    };
    ConditionGroupService.prototype.makeRequest = function (path) {
        var _this = this;
        var opts = this._apiRoot.getDefaultRequestOptions();
        return this._http
            .get(path, opts)
            .map(function (res) {
            var json = res.json();
            _this.loggerService.info('ConditionGroupService', 'makeRequest-Response', json);
            return json;
        })
            .catch(function (err, source) {
            if (err && err.status === HttpCode.NOT_FOUND) {
                _this.loggerService.error('Could not retrieve ' + _this._typeName + ' : 404 path not valid.', path);
            }
            else if (err) {
                _this.loggerService.info('Could not retrieve' + _this._typeName + ': Response status code: ', err.status, 'error:', err, path);
            }
            return Observable.empty();
        });
    };
    ConditionGroupService.prototype.all = function (ruleKey, keys) {
        var _this = this;
        return Observable.from(keys).flatMap(function (groupKey) {
            return _this.get(ruleKey, groupKey);
        });
    };
    ConditionGroupService.prototype.allAsArray = function (ruleKey, keys) {
        return this.all(ruleKey, keys).reduce(function (acc, group) {
            acc.push(group);
            return acc;
        }, []);
    };
    ConditionGroupService.prototype.get = function (ruleKey, key) {
        var _this = this;
        var result;
        result = this.makeRequest(this._getPath(ruleKey, key)).map(function (json) {
            json.id = key;
            _this.loggerService.info('ConditionGroupService', 'creatingConditionGroupFromJson≠≠');
            return new ConditionGroupModel(json);
        });
        return result;
    };
    ConditionGroupService.prototype.createConditionGroup = function (ruleId, model) {
        this.loggerService.info('ConditionGroupService', 'add', model);
        if (!model.isValid()) {
            throw new Error("This should be thrown from a checkValid function on the model,\n                        and should provide the info needed to make the user aware of the fix");
        }
        var json = ConditionGroupService.toJson(model);
        var opts = this._apiRoot.getDefaultRequestOptions();
        var path = this._getPath(ruleId);
        var add = this._http.post(path, JSON.stringify(json), opts).map(function (res) {
            var json = res.json();
            model.key = json.id;
            return model;
        });
        return add.catch(this._catchRequestError('add'));
    };
    ConditionGroupService.prototype.updateConditionGroup = function (ruleId, model) {
        this.loggerService.info('ConditionGroupService', 'save');
        if (!model.isValid()) {
            throw new Error("This should be thrown from a checkValid function on the model,\n                        and should provide the info needed to make the user aware of the fix.");
        }
        if (!model.isPersisted()) {
            this.createConditionGroup(ruleId, model);
        }
        else {
            var json = ConditionGroupService.toJson(model);
            var opts = this._apiRoot.getDefaultRequestOptions();
            var save = this._http
                .put(this._getPath(ruleId, model.key), JSON.stringify(json), opts)
                .map(function (res) {
                return model;
            });
            return save.catch(this._catchRequestError('save'));
        }
    };
    ConditionGroupService.prototype.remove = function (ruleId, model) {
        var opts = this._apiRoot.getDefaultRequestOptions();
        var remove = this._http
            .delete(this._getPath(ruleId, model.key), opts)
            .map(function (res) {
            return model;
        });
        return remove.catch(this._catchRequestError('remove'));
    };
    ConditionGroupService.prototype._getPath = function (ruleKey, key) {
        var p = this._baseUrl + '/' + ruleKey + '/conditionGroups/';
        if (key) {
            p = p + key;
        }
        return p;
    };
    ConditionGroupService.prototype._catchRequestError = function (operation) {
        var _this = this;
        return function (err) {
            if (err && err.status === HttpCode.NOT_FOUND) {
                _this.loggerService.info('Could not ' + operation + ' Condition: URL not valid.');
            }
            else if (err) {
                _this.loggerService.info('Could not ' + operation + ' Condition.', 'response status code: ', err.status, 'error:', err);
            }
            return Observable.empty();
        };
    };
    return ConditionGroupService;
}());
export { ConditionGroupService };
ConditionGroupService.decorators = [
    { type: Injectable },
];
/** @nocollapse */
ConditionGroupService.ctorParameters = function () { return [
    { type: ApiRoot, },
    { type: Http, },
    { type: LoggerService, },
]; };
//# sourceMappingURL=ConditionGroup.js.map