import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Rx';
import { ApiRoot } from 'dotcms-js/dotcms-js';
import { Http } from '@angular/http';
import { ActionModel } from './Rule';
import { UNKNOWN_RESPONSE_ERROR, CwError, SERVER_RESPONSE_ERROR, NETWORK_CONNECTION_ERROR, CLIENTS_ONLY_MESSAGES } from 'dotcms-js/dotcms-js';
import { LoggerService } from 'dotcms-js/dotcms-js';
import { HttpCode } 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 ActionService = (function () {
    function ActionService(apiRoot, http, loggerService) {
        this.loggerService = loggerService;
        this._typeName = 'Action';
        this._apiRoot = apiRoot;
        this._http = http;
        this._actionsEndpointUrl = apiRoot.baseUrl + "api/v1/sites/" + apiRoot.siteId + "/ruleengine/actions/";
    }
    ActionService.fromJson = function (type, json) {
        var ra = new ActionModel(json.key, type, json.priority);
        Object.keys(json.parameters).forEach(function (key) {
            var param = json.parameters[key];
            ra.setParameter(key, param.value);
        });
        return ra;
    };
    ActionService.toJson = function (action) {
        var json = {};
        json.actionlet = action.type.key;
        json.priority = action.priority;
        json.parameters = action.parameters;
        return json;
    };
    ActionService.prototype.makeRequest = function (childPath) {
        var _this = this;
        var opts = this._apiRoot.getDefaultRequestOptions();
        var path = this._actionsEndpointUrl;
        if (childPath) {
            path = "" + path + childPath;
        }
        return this._http
            .get(path, opts)
            .map(function (res) {
            return res.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.debug('Could not retrieve' + _this._typeName + ': Response status code: ', err.status, 'error:', err, path);
            }
            return Observable.empty();
        });
    };
    ActionService.prototype.allAsArray = function (ruleKey, keys, ruleActionTypes) {
        return this.all(ruleKey, keys, ruleActionTypes).reduce(function (acc, item) {
            acc.push(item);
            return acc;
        }, []);
    };
    ActionService.prototype.all = function (ruleKey, keys, ruleActionTypes) {
        var _this = this;
        return Observable.from(keys).flatMap(function (groupKey) {
            return _this.get(ruleKey, groupKey, ruleActionTypes);
        });
    };
    ActionService.prototype.get = function (ruleKey, key, ruleActionTypes) {
        return this.makeRequest(key).map(function (json) {
            json.id = key;
            json.key = key;
            return ActionService.fromJson(ruleActionTypes[json.actionlet], json);
        });
    };
    ActionService.prototype.createRuleAction = function (ruleId, model) {
        this.loggerService.debug('Action', 'add', model);
        if (!model.isValid()) {
            throw new Error("This should be thrown from a checkValid function on the model,\nand should provide the info needed to make the user aware of the fix.");
        }
        var json = ActionService.toJson(model);
        json.owningRule = ruleId;
        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'));
    };
    ActionService.prototype.updateRuleAction = function (ruleId, model) {
        this.loggerService.debug('actionService', '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.createRuleAction(ruleId, model);
        }
        else {
            var json = ActionService.toJson(model);
            json.owningRule = ruleId;
            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'));
        }
    };
    ActionService.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'));
    };
    ActionService.prototype._getPath = function (ruleKey, key) {
        var p = this._actionsEndpointUrl;
        if (key) {
            p = p + key;
        }
        return p;
    };
    ActionService.prototype._catchRequestError = function (operation) {
        var _this = this;
        return function (response, original) {
            if (response) {
                if (response.status === HttpCode.SERVER_ERROR) {
                    if (response.text() && response.text().indexOf('ECONNREFUSED') >= 0) {
                        throw new CwError(NETWORK_CONNECTION_ERROR, CLIENTS_ONLY_MESSAGES[NETWORK_CONNECTION_ERROR]);
                    }
                    else {
                        throw new CwError(SERVER_RESPONSE_ERROR, response.headers.get('error-message'));
                    }
                }
                else if (response.status === HttpCode.NOT_FOUND) {
                    _this.loggerService.error('Could not execute request: 404 path not valid.');
                    throw new CwError(UNKNOWN_RESPONSE_ERROR, response.headers.get('error-message'));
                }
                else {
                    _this.loggerService.debug('Could not execute request: Response status code: ', response.status, 'error:', response);
                    throw new CwError(UNKNOWN_RESPONSE_ERROR, response.headers.get('error-message'));
                }
            }
            return null;
        };
    };
    return ActionService;
}());
export { ActionService };
ActionService.decorators = [
    { type: Injectable },
];
/** @nocollapse */
ActionService.ctorParameters = function () { return [
    { type: ApiRoot, },
    { type: Http, },
    { type: LoggerService, },
]; };
//# sourceMappingURL=Action.js.map