// (C) Copyright 2020 Hewlett-Packard Enterprise Company, L.P.

define(['hp/core/Localizer', 'jquery', 'lib/jquery.browser'],

function(localizer) {"use strict";
    var FormUploader = (function() {

        function FormUploader(options) {

            // Helper variable to create unique names for the transport iframes:
            var counter = 0;
            
            // Error code returned when IE8/9 fails to put upload response in iframe
            var IE8Or9_EMPTY_RESPONSE_ERROR_CODE = "IE8Or9EmptyResponse";
            
            function isIE8Or9() {
                if ($.browser.msie && (parseInt($.browser.version, 10) === 8 || parseInt($.browser.version, 10) === 9)) {
                    return true;
                }
                return false;
            }

            function parseResponse(response) {
                var result = {
                        type : 'error',
                        code : '400',
                        response: {'text': response }
                    },
                    responseObj;
                if (response) {
                    try {
                        responseObj = $.parseJSON(response);
                        if (!(responseObj && responseObj.hasOwnProperty('message') &&
                            responseObj.hasOwnProperty('errorCode') && responseObj.hasOwnProperty('recommendedActions'))) {
                            result.type = 'success';
                            result.code = '200';
                            result.response = {'iframe': response };
                        }
                    } catch (e) {
                        result.response.text = JSON.stringify({
                            message : response,
                            errorCode : "",
                            recommendedActions : []
                        });
                    }
                } else {
                    var responseTextInfo = {
                            message : localizer.getString('core.file.upload.error.emptyResponse'),
                            errorCode : "",
                            recommendedActions : []
                        };
                    if (isIE8Or9()) {
                        responseTextInfo.errorCode = IE8Or9_EMPTY_RESPONSE_ERROR_CODE;
                    }
                    result.response.text = JSON.stringify(responseTextInfo);
                }
                return result;
            }
            
            // The iframe transport accepts three additional options:
            // options.fileInput: a jQuery collection of file input fields
            // options.paramName: the parameter name for the file form data,
            //  overrides the name property of the file input field(s),
            //  can be a string or an array of strings.
            // options.formData: an array of objects with name and value properties,
            //  equivalent to the return data of .serializeArray(), e.g.:
            //  [{name: 'a', value: 1}, {name: 'b', value: 2}]
            $.ajaxTransport('iframe', function (options) {
                if (options.async && (options.type === 'POST' || options.type === 'GET')) {
                    var form,
                        iframe,
                        uploadDoneEvent;
                        
                    // IE9 and IE8 don't consistently fire the load 
                    // event so use the readystatechange event instead
                    if (isIE8Or9()) {
                        uploadDoneEvent = 'readystatechange';
                    } else {
                        uploadDoneEvent = 'load';
                    }
                    
                    return {
                        send: function (_, completeCallback) {
                            //style="display:block;height:600px;position:absolute;bottom:0px;left:0px;width:1500px;background-color:white;z-index:400"
                            form = $('<form style="display:none;"></form>');
                            // javascript:false as initial iframe src
                            // prevents warning popups on HTTPS in IE6.
                            // IE versions below IE8 cannot set the name property of
                            // elements that have already been added to the DOM,
                            // so we set the name along with the iframe HTML markup:
                            // style="width:100%;height:100%;display:block"
                            iframe = $('<iframe src="javascript:false;" name="iframe-transport-' + (counter += 1) + '"></iframe>')
                                .bind('load', function () {
                                var fileInputClones,
                                    paramNames = $.isArray(options.paramName) ?
                                        options.paramName : [options.paramName];
                                iframe
                                .unbind('load')
                                .bind(uploadDoneEvent, function () {
                                    var response, iframeContents, result;
                                    // Wrap in a try/catch block to catch exceptions thrown
                                    // when trying to access cross-domain iframe contents:
                                    try {
                                        iframeContents = iframe.contents();
                                        // Google Chrome and Firefox do not throw an
                                        // exception when calling iframe.contents() on
                                        // cross-domain requests, so we unify the response:
                                        if (!iframeContents.length || !iframeContents[0].firstChild) {
                                            throw new Error();
                                        }
                                        response = $(iframeContents[0].body).text();
                                    } catch (e) {
                                        response = JSON.stringify({
                                            message : localizer.getString('core.file.upload.error.accessDenied', [e.message]),
                                            errorCode : "",
                                            recommendedActions : []
                                        });
                                    }
                                    
                                    // The complete callback returns the
                                    // iframe content document in text form as response object.
                                    result = parseResponse(response);
                                    completeCallback(result.code, result.type, result.response);
                                    
                                    // Fix for IE endless progress bar activity bug
                                    // (happens on form submits to iframe targets):
                                    $('<iframe src="javascript:false;"></iframe>').appendTo(form);
                                    form.remove();
                                });
                                form.prop('target', iframe.prop('name'))
                                    .prop('action', options.url)
                                    .prop('method', options.type);
                                if (options.formData) {
                                    $.each(options.formData, function (index, field) {
                                        $('<input type="hidden"/>')
                                            .prop('name', field.name)
                                            .val(field.value)
                                            .appendTo(form);
                                    });
                                }
                                if (options.fileInput && options.fileInput.length && options.type === 'POST') {
                                    fileInputClones = options.fileInput.clone();
                                    // Insert a clone for each file input field:
                                    options.fileInput.after(function (index) {
                                        return fileInputClones[index];
                                    });
                                    options.fileInput.removeAttr('disabled');
                                    if (options.paramName) {
                                        options.fileInput.each(function (index) {
                                            $(this).prop(
                                                    'name',
                                                    paramNames[index] || options.paramName
                                            );
                                        });
                                    }
                                    // Appending the file input fields to the hidden form
                                    // removes them from their original location:
                                    form.append(options.fileInput)
                                        .prop('enctype', 'multipart/form-data')
                                        // enctype must be set as encoding for IE:
                                        .prop('encoding', 'multipart/form-data');
                                }
                                form.submit();
                                // Insert the file input fields at their original location
                                // by replacing the clones with the originals:
                                if (fileInputClones && fileInputClones.length) {
                                    options.fileInput.each(function (index, input) {
                                        var clone = $(fileInputClones[index]);
                                        $(input).prop('name', clone.prop('name'));
                                        clone.replaceWith(input);
                                    });
                                }

                            });
                            form.append(iframe).appendTo(document.body);
                        },
                        abort: function () {
                            if (iframe) {
                                // javascript:false as iframe src aborts the request
                                // and prevents warning popups on HTTPS in IE6.
                                // concat is used to avoid the "Script URL" JSLint error:
                                iframe
                                .unbind(uploadDoneEvent)
                                .prop('src', 'javascript'.concat(':false;'));
                            }
                            if (form) {
                                form.remove();
                            }
                        }
                    };
                }
            });

            // The iframe transport returns the iframe content document as response.
            // The following adds converters from iframe to text and json:
            $.ajaxSetup({
                converters: {
                    'iframe text': function (response) {
                        return response;
                    },
                    'iframe json': function (response) {
                        var obj;
                        try {
                            obj = $.parseJSON(response);
                        }
                        catch (error) {
                            obj = response;
                        }
                        return obj;
                    }
                }
            });
        }
        
        return new FormUploader();
    }());
    
    return FormUploader;
});

