import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Rx';
import { ApiRoot } from 'dotcms-js/dotcms-js';
import { Http } from '@angular/http';
import { ConditionModel } from './Rule';
import { HttpCode } from 'dotcms-js/dotcms-js';
import { LoggerService } from 'dotcms-js/dotcms-js';
// tslint:disable-next-line:no-unused-variable
var noop = function () {
    var arg = [];
    for (var _i = 0; _i < arguments.length; _i++) {
        arg[_i] = arguments[_i];
    }
};
var ConditionService = (function () {
    function ConditionService(apiRoot, http, loggerService) {
        this.loggerService = loggerService;
        this._apiRoot = apiRoot;
        this._http = http;
        this._baseUrl = apiRoot.baseUrl + "api/v1/sites/" + apiRoot.siteId + "/ruleengine/conditions";
    }
    ConditionService.toJson = function (condition) {
        var json = {};
        json.id = condition.key;
        json.conditionlet = condition.type.key;
        json.priority = condition.priority;
        json.operator = condition.operator;
        json.values = condition.parameters;
        return json;
    };
    ConditionService.fromServerConditionTransformFn = function (condition) {
        var conditionModel = null;
        try {
            conditionModel = new ConditionModel(condition);
            var values_1 = condition['values'];
            Object.keys(values_1).forEach(function (key) {
                var x = values_1[key];
                conditionModel.setParameter(key, x.value, x.priority);
                // tslint:disable-next-line:no-console
                console.log('ConditionService', 'setting parameter', key, x);
            });
        }
        catch (e) {
            // tslint:disable-next-line:no-console
            console.error('Error reading Condition.', e);
            throw e;
        }
        return conditionModel;
    };
    ConditionService.prototype.makeRequest = function (childPath) {
        var _this = this;
        var opts = this._apiRoot.getDefaultRequestOptions();
        return this._http
            .get(this._baseUrl + '/' + childPath, opts)
            .map(function (res) {
            return res.json();
        })
            .catch(function (err, source) {
            if (err && err.status === HttpCode.NOT_FOUND) {
                _this.loggerService.info('Could not retrieve Condition Types: URL not valid.');
            }
            else if (err) {
                _this.loggerService.info('Could not retrieve Condition Types.', 'response status code: ', err.status, 'error:', err);
            }
            return Observable.empty();
        });
    };
    ConditionService.prototype.listForGroup = function (group, conditionTypes) {
        var _this = this;
        return Observable.from(Object.keys(group.conditions))
            .flatMap(function (conditionId) {
            return _this.get(conditionId, conditionTypes);
        })
            .reduce(function (acc, entity) {
            acc.push(entity);
            return acc;
        }, []);
    };
    ConditionService.prototype.get = function (conditionId, conditionTypes) {
        var conditionModelResult;
        conditionModelResult = this.makeRequest(conditionId);
        return conditionModelResult.map(function (entity) {
            entity.id = conditionId;
            entity._type = conditionTypes ? conditionTypes[entity.conditionlet] : null;
            return ConditionService.fromServerConditionTransformFn(entity);
        });
    };
    ConditionService.prototype.add = function (groupId, model) {
        // this.loggerService.info("api.rule-engine.ConditionService", "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 = ConditionService.toJson(model);
        json.owningGroup = groupId;
        var opts = this._apiRoot.getDefaultRequestOptions();
        var add = this._http
            .post(this._baseUrl + '/', JSON.stringify(json), opts)
            .map(function (res) {
            var json = res.json();
            model.key = json.id;
            return model;
        });
        return add.catch(this._catchRequestError('add'));
    };
    ConditionService.prototype.save = function (groupId, model) {
        this.loggerService.info('api.rule-engine.ConditionService', 'save', 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.");
        }
        if (!model.isPersisted()) {
            this.add(groupId, model);
        }
        else {
            var json = ConditionService.toJson(model);
            json.owningGroup = groupId;
            var opts = this._apiRoot.getDefaultRequestOptions();
            var body = JSON.stringify(json);
            var save = this._http
                .put(this._baseUrl + '/' + model.key, body, opts)
                .map(function (res) {
                return model;
            });
            return save.catch(this._catchRequestError('save'));
        }
    };
    ConditionService.prototype.remove = function (model) {
        var opts = this._apiRoot.getDefaultRequestOptions();
        var remove = this._http
            .delete(this._baseUrl + '/' + model.key, opts)
            .map(function (res) {
            return model;
        });
        return remove.catch(this._catchRequestError('remove'));
    };
    ConditionService.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 ConditionService;
}());
export { ConditionService };
ConditionService.decorators = [
    { type: Injectable },
];
/** @nocollapse */
ConditionService.ctorParameters = function () { return [
    { type: ApiRoot, },
    { type: Http, },
    { type: LoggerService, },
]; };
//# sourceMappingURL=Condition.js.map