"use strict";

var SharedConstants = require("../constants/SharedConstants");
var UtilHttpStatus = require("./UtilHttpStatus");

var FORBIDDEN_ERROR = "ForbiddenError";
var NOT_FOUND_ERROR = "NotFoundError";
var DELETED_ERROR = "DeletedError";
var FORBIDDEN_MESSAGE = "Access Restricted";
var FORBIDDEN_TEMPLATE_MESSAGE = "Access to the template for this document is restricted and no alternate template " +
    "is configured. Please configure an alternate template to be able to access this document";
var SERVER_UNRESPONSE_ERROR = "ServerUnResponseError";

module.exports = {
    NOT_FOUND_ERROR: NOT_FOUND_ERROR,
    DELETED_ERROR: DELETED_ERROR,
    FORBIDDEN_MESSAGE: FORBIDDEN_MESSAGE,
    FORBIDDEN_TEMPLATE_MESSAGE: FORBIDDEN_TEMPLATE_MESSAGE,
    FORBIDDEN_ERROR: FORBIDDEN_ERROR,
    SERVER_UNRESPONSE_ERROR: SERVER_UNRESPONSE_ERROR,
    createError: function (message, name) {
        logger.error(message);
        var err = new Error(message);
        err.name = name;
        return err;
    },
    createErrorObject: function(err) {
        // if the error is a string, create an error object. Otherwise return the error
        if (err instanceof Error) {
            return err;
        } else if (typeof err === 'string' || err instanceof String) {
            return new Error(err);
        }
    },
    createForbiddenError: function(doc, actionType) {
        var message;
        if (doc)  {
            if (doc.systemHeader &&
                doc.systemHeader.systemType === SharedConstants.SYSTEM_TYPE_TEMPLATE &&
                actionType === SharedConstants.OPERATION_TYPE_READ) {
                message = FORBIDDEN_TEMPLATE_MESSAGE;
            } else {
                message = actionType + " access denied on document " + doc.documentId;
            }
        }

        return this.createError(message, FORBIDDEN_ERROR);
    },
    limitErrorMessage: function(message) {
        if(message && message.length > SharedConstants.DEFAULT_MESSAGE_LENGTH) {
            message = message.substring(0, SharedConstants.DEFAULT_MESSAGE_LENGTH) + "...";
        }
        return message;
    }
};