// (C) Copyright 2020 Hewlett-Packard Enterprise Company, L.P.
/**
 * HpsumRest
 * This is require to provide simulated functions for REST calls. Later this needs to be removed once complete REST API are integrated with UI.
 */
define(['hp/services/IndexService', 'hp/services/REST','hp/model/Session','hp/core/Localizer','hp/services/Encoder', 'jquery'],
function(indexService, restService,session,Localizer, encoder) {"use strict";

    function getErrorInfo(uri, jqXHR, textStats, errorThrown, encodeErrors) {
        var response;
        try {
            response = JSON.parse(jqXHR.responseText);
            if (response) {
                // Adapt new fields from ErrorMessage onto the old style to minimize changes needed by downstream code.
                // Map message onto errorMessage and recommendedActions[] onto resolution.
                // DEPRECATED: Will be removed in sprint 23.
                if (!response.hasOwnProperty('errorMessage') && response.hasOwnProperty('message')) {
                    response.errorMessage = response.message;
                }
                if (!response.hasOwnProperty('resolution') && response.hasOwnProperty('recommendedActions')) {
                    response.resolution = response.recommendedActions ? response.recommendedActions.join('\n') : null;
                }
            }
        }
        catch(err) {
             // the components are responsible for handling an error as they know the context
            // but here we give a general message as the underlying cause
            
            response = {
                errorMessage: Localizer.getString('hpsum.host.connectionError', [window.location.hostname]),
                message: Localizer.getString('hpsum.host.connectionError', [window.location.hostname])
            };
        }
        if (encodeErrors) {
            encoder.encodeObject(response);
        }
        return response;
    }

    function onError(uri, handlers, jqXHR, textStats, errorThrown, encodeErrors) {
        var errorInfo;

        errorInfo = getErrorInfo(uri, jqXHR, textStats, errorThrown, encodeErrors);
        if (handlers.error) {
            handlers.error(errorInfo, jqXHR);
        }
    }

     /**
     * Create a set of options for an ajax call which is the combination of the standard ones,
     * and any the user passed in. Adds data parameter if included.
     */
    function ajaxOptions (uri,type,handlers,options,data,etag) {
        
        // Determine how to handle options param
        var hasOptions = false,
            async = true,
            encodeResults = true,
            encodeErrors = true;
        
        if (options){
            if (typeof(options)=='boolean') {
                hasOptions=false;
                // Reverse polarity because old method signature was synchronous
                async = options?false:true;
            }
            else {
                if (typeof(options)=='object') {
                    hasOptions = true;
                    // Allow callers to turn off response encoding just in case untouched responses are needed.
                    if (options.hasOwnProperty('encodeResults')) {
                        encodeResults = options.encodeResults;
                    }
                    if (options.hasOwnProperty('encodeErrors')) {
                        encodeErrors = options.encodeErrors;
                    }
                }
            }
        }
        
        // Do initial setup of options, this is the original version of this function
        var finalOptions = {
            url : uri,
            type : type,
            async : async,
            success : function(data, status, xhr) {
                if (encodeResults) {
                    encoder.encodeObject(data);
                }
                handlers.success(data, status, xhr);
                performance.endOperation(uri);
            },
            error : function (jqXHR, textStats, errorThrown) {
                onError(uri, handlers, jqXHR, textStats, errorThrown, encodeErrors);
            },
            contentType : "application/json",
            dataType : "json",
            headers : {
                "auth" : session.getToken(),
                "Accept-language" : session.getLanguage()
            }
        };
        
        var myEtag = etag;
        var apiVersion = 1;
        if (hasOptions) {
            if (options && options.hpEtag) {
                myEtag = options.hpEtag;
            }
            if (options && options.apiVersion) {
                apiVersion = options.apiVersion;
            }
            $.extend(true,finalOptions,options);  
            delete finalOptions.hpEtag;
            delete finalOptions.apiVersion;
        }
        if(myEtag){
            var etagType = (type=="GET")?"If-None-Match":"If-Match";
            finalOptions.headers[etagType] = myEtag;
        }
        finalOptions.headers['X-API-Version'] = apiVersion.toString();
        if (data){
            finalOptions.data = data;
        }
        return finalOptions;
    }

    function ajax(uri, type, handlers, options,data,etag) {
       // performance.beginOperation(uri);
        $.ajax(ajaxOptions(uri, type, handlers, options, data, etag));
    }



    return {
        
        getURI : function(uri, handlers, synchronous) {
            	indexService.simulatedGetURI(uri, handlers);
        },
        postObject : function(uri, object, handlers, options) {
             ajax(uri, 'POST', handlers, options, JSON.stringify(object)); 
        }
    };
});
