/*-
 * ~~~~~~licensing~~~~~~
 * plugin
 * ==========
 * Copyright (C) 2020 - 2025 EmDev LLC
 * ==========
 * You may not use this file except in accordance with the License Terms of the Copyright
 * Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property
 * rights to the Software and any copies are the property of the Copyright Holder. Unless
 * it is explicitly allowed the Copyright Holder, the User is prohibited from using the
 * Software for commercial purposes to provide services to third parties.
 * 
 * The Copyright Holder hereby declares that the Software is provided on an "AS IS".
 * Under no circumstances does the Copyright Holder guarantee or promise that the
 * Software provided by him will be suitable or not suitable for the specific purposes
 * of the User, that the Software will meet all commercial and personal subjective
 * expectations of the User, that the Software will work properly, without technical
 * errors, quickly and uninterruptedly.
 * 
 * Under no circumstances shall the Copyright Holder or its Affiliates is not liable
 * to the User for any direct or indirect losses of the User, his expenses or actual
 * damage, including, downtime; loss of bussines; lost profit; lost earnings; loss
 * or damage to data, property, etc.
 * ~~~~~~/licensing~~~~~~
 */
var Entaxy1CCommunication;
(function (Entaxy1CCommunication) {
    Entaxy1CCommunication._module.factory('soapService', ['$q', '$http', '$location', 'xml2JsonService',
        function($q, $http, $location, xml2JsonService) {
            return {
                execute: function (body, forwardedUser, context) {
                    return execute(body, forwardedUser, context);
                }
            };

            function execute(body, forwardedUser, context) {

                let deferred = $q.defer();
                let cxfContext = '/cxf';
                let url = getBaseLocation() + cxfContext + context;

                $http.defaults.headers.common.Authorization = 'Basic c3lzNDpzeXM0';
                $http({
                    'url': url,
                    'method': 'POST',
                    'headers': {
                        'X-ForwardedUser' : forwardedUser
                    },
                    'data': '<?xml version="1.0" encoding="UTF-8"?>'+
                        '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns="http://www.entaxy.ru/ExchangeTypes/1.0">' +
                            '<soapenv:Header/>' +
                            '<soapenv:Body>' + body + '</soapenv:Body>' +
                        '</soapenv:Envelope>'
                })
                .then(function(response) {

                    Entaxy1CCommunication.log.info('response data ' + response.data);

                    let jsonResponse = xml2JsonService.xml2json(response.data);

                    Entaxy1CCommunication.log.info('parsed response data ' + JSON.stringify(jsonResponse));

                    let body = jsonResponse['soap:Envelope'][0]['soap:Body'][0];
                    let bodyResponse = body.response[0];

                    let status = bodyResponse.status[0]['#text'];

                    if (status === '200') {
                        deferred.resolve(bodyResponse);
                    } else if (status === '204') {
                        deferred.resolve(null);
                    } else {
                        deferred.reject('Error status: ' + status);
                    }
                }, function(response) {
                    deferred.reject(response);
                }).catch(function(fallback) {
                    Entaxy1CCommunication.log.error(fallback);
                });
                return deferred.promise;
            };

            function getBaseLocation() {
                let port = $location.port();
                return $location.protocol() + '://' + $location.host() + (port ? (':' + port) : '');
            }

        }
    ]);
})(Entaxy1CCommunication || (Entaxy1CCommunication = {}));
