var axios = require('axios');
const path = require('path');

function soapLogin(type, address, port, username, password, agent) {

    return new Promise((resolve, reject) => {

        // URL richiesta di login.
        const url = type === 'BARCO' ? ("https://" + address + ":" + port) : "http://" + address + ":" + port + "/dc/dcp/ws/v1/SessionManagement";
        const args = type === 'BARCO' ? ('<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:sms="http://www.barco.com/sms/sms_1"><soap:Header/><soap:Body><sms:Login><sms:userName>' + username + '</sms:userName><sms:password>' + password + '</sms:password><sms:sessionInfo></sms:sessionInfo></sms:Login></soap:Body></soap:Envelope>')
            : ('<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:v1="http://www.doremilabs.com/dc/dcp/ws/v1_0"><soapenv:Header/><soapenv:Body><v1:Login><username>' + username + '</username><password>' + password + '</password></v1:Login></soapenv:Body></soapenv:Envelope>');

        //const httpAgent = new http.Agent({ keepAlive: true });

        const options = {

            baseURL: url,
            method: 'post',
            timeout: 10000,
            headers: {
                "Accept-Encoding": "gzip,deflate",
                "Content-Type": "application/soap+xml;charset=UTF-8;charset=UTF-8",
                'SOAPAction': '',
                'Connection': 'Keep-Alive'
            },
            auth: {},
            httpsAgent: agent,
            data: args,

        }

        //console.log(args);

        axios(options).then(res => {

            return resolve(res.data);

        }).catch(error => {

            //console.log(error);
            return resolve(undefined);

        })



    });

}

function soapAPI(type, address, port, api_type, agent, uuid_login = '', options = {}) {

    let options_ = options;

    return new Promise((resolve, reject) => {

        var url = "";
        var body = "";

        if (type === 'BARCO') {

            url = "https://" + address + ":" + port;

            // GetProductInformation dal wsdl di Barco Alchemny
            if (api_type === 'get_product') {
                body = '<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:sms="http://www.barco.com/sms/sms_1"><soap:Header/><soap:Body><sms:GetProductInformation/></soap:Body></soap:Envelope>';
            }
            if (api_type === 'get_certificate') {
                body = '<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:sms="http://www.barco.com/sms/sms_1"><soap:Header/><soap:Body><sms:GetCertificateList/></soap:Body></soap:Envelope>';
            }
            if (api_type === 'get_certificate_pem') {
                body = '<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:sms="http://www.barco.com/sms/sms_1"><soap:Header/><soap:Body><sms:GetCertificate><sms:certificateKind>' + options_.kind + '</sms:certificateKind></sms:GetCertificate></soap:Body></soap:Envelope>';
            }
            if (api_type === 'get_serial_audio') {
                body = '<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:sms="http://www.barco.com/sms/sms_1"><soap:Header/><soap:Body><sms:GetImmersiveSoundRendererInfo/></soap:Body></soap:Envelope>';
            }
            if (api_type === 'get_storage') {
                body = '<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:sms="http://www.barco.com/sms/sms_1"><soap:Header/><soap:Body><sms:GetStorageStatus/></soap:Body></soap:Envelope>';
            }
            if (api_type === 'logout') {
                body = '<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:sms="http://www.barco.com/sms/sms_1"><soap:Header/><soap:Body><sms:Logout/></soap:Body></soap:Envelope>';
            }
            if (api_type === 'get_cpllist') {
                body = '<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:sms="http://www.barco.com/sms/sms_1"><soap:Header/><soap:Body><sms:GetCplList/></soap:Body></soap:Envelope>';
            }
            if (api_type === 'get_kdmlist') {
                body = '<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:sms="http://www.barco.com/sms/sms_1"><soap:Header/><soap:Body><sms:GetKdmList/></soap:Body></soap:Envelope>';
            }
            if (api_type === 'delete_kdm') {
                let id_kdm_remove = "";
                options_.kdmList.forEach(kdm => { id_kdm_remove += "<sms:string>" + kdm + "</sms:string>"; });
                body = '<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:sms="http://www.barco.com/sms/sms_1"><soap:Header/><soap:Body><sms:DeleteKdmList><sms:idList>' + id_kdm_remove + '</sms:idList></sms:DeleteKdmList></soap:Body></soap:Envelope>';
            }
            if (api_type === 'ingest_kdm') {
                body = options_.xml;
            }
            if (api_type === 'ingest_cpl') {

                const uri = 'nfs://' + options_.datastore + '/datastore/' + path.join(options_.folder).replace(/\\/g, '/');
                body = '<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:sms="http://www.barco.com/sms/sms_1"><soap:Header/><soap:Body><sms:AddIngestJob><sms:jobToAdd><sms:Id></sms:Id><sms:Title>' + options_.title + '</sms:Title><sms:ExternalStorageUrl>' + uri + '</sms:ExternalStorageUrl><sms:ItemId>' + options_.uuid + '</sms:ItemId><sms:ItemType>CPL</sms:ItemType></sms:jobToAdd></sms:AddIngestJob></soap:Body></soap:Envelope>';

                //console.log(body);

            }

            if (api_type === 'get_task') {

                body = '<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:sms="http://www.barco.com/sms/sms_1"><soap:Header/><soap:Body><sms:GetIngestJobList/></soap:Body></soap:Envelope>';

            }

        }

        if (type.toUpperCase().indexOf('DOLBY') >= 0) {

            if (api_type === 'get_product') {
                url = "http://" + address + ":" + port + "/dc/dcp/ws/v1/SystemInformation";
                body = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:v1="http://www.doremilabs.com/dc/dcp/ws/v1_0"><soapenv:Header/><soapenv:Body><v1:GetProductInformation><sessionId>' + uuid_login + '</sessionId></v1:GetProductInformation></soapenv:Body></soapenv:Envelope>';
            }
            if (api_type === 'get_certificate') {
                url = "http://" + address + ":" + port + "/dc/dcp/ws/v1/SystemInformation";
                body = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:v1="http://www.doremilabs.com/dc/dcp/ws/v1_0"><soapenv:Header/><soapenv:Body><v1:GetCertificateList><sessionId>' + uuid_login + '</sessionId></v1:GetCertificateList></soapenv:Body></soapenv:Envelope>';
            }
            if (api_type === 'get_storage') {
                url = "http://" + address + ":" + port + "/dc/dcp/ws/v1/StorageManagement";
                body = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:v1="http://www.doremilabs.com/dc/dcp/ws/v1_0"><soapenv:Header/><soapenv:Body><v1:GetStorageList><sessionId>' + uuid_login + '</sessionId></v1:GetStorageList></soapenv:Body></soapenv:Envelope>';
            }
            if (api_type === 'logout') {
                url = "http://" + address + ":" + port + "/dc/dcp/ws/v1/SessionManagement";
                body = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:v1="http://www.doremilabs.com/dc/dcp/ws/v1_0"><soapenv:Header/><soapenv:Body><v1:Logout><sessionId>' + uuid_login + '</sessionId></v1:Logout></soapenv:Body></soapenv:Envelope>';
            }
            if (api_type === 'get_cpllist') {
                url = "http://" + address + ":" + port + "/dc/dcp/ws/v1/CPLManagement";
                body = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:v1="http://www.doremilabs.com/dc/dcp/ws/v1_0"><soapenv:Header/><soapenv:Body><v1:GetCPLListInfo><sessionId>' + uuid_login + '</sessionId></v1:GetCPLListInfo></soapenv:Body></soapenv:Envelope>';
            }
            if (api_type === 'get_kdmlist') {
                url = "http://" + address + ":" + port + "/dc/dcp/ws/v1/KDMManagement";
                body = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:v1="http://www.doremilabs.com/dc/dcp/ws/v1_0"><soapenv:Header/><soapenv:Body><v1:GetKDMListInfo><sessionId>' + uuid_login + '</sessionId></v1:GetKDMListInfo></soapenv:Body></soapenv:Envelope>';
            }
            if (api_type === 'delete_kdm') {
                url = "http://" + address + ":" + port + "/dc/dcp/ws/v1/KDMManagement";
                body = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:v1="http://www.doremilabs.com/dc/dcp/ws/v1_0"><soapenv:Header/><soapenv:Body><v1:DeleteKDM><sessionId>' + uuid_login + '</sessionId><kdmId>' + options_.id_kdm + '</kdmId></v1:DeleteKDM></soapenv:Body></soapenv:Envelope>';
            }
            if (api_type === 'ingest_kdm') {
                url = "http://" + address + ":" + port + "/dc/dcp/ws/v1/KDMManagement";
                body = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:v1="http://www.doremilabs.com/dc/dcp/ws/v1_0"><soapenv:Header/><soapenv:Body><v1:SetKDMContent><sessionId>' + uuid_login + '</sessionId><content>' + options_.kdm64 + '</content></v1:SetKDMContent></soapenv:Body></soapenv:Envelope>';
            }
            if (api_type === 'ingest_cpl') {
                url = "http://" + address + ":" + port + "/dc/dcp/ws/v1/IngestManagement";
                const uri = 'share://datastore/' + path.join(options_.folder, options_.filename).replace(/\\/g, '/');
                body = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:v1="http://www.doremilabs.com/dc/dcp/ws/v1_0" xmlns:ing="http://www.doremilabs.com/dc/dcp/ws/v1/schemas/ingestmanagement"><soapenv:Header/><soapenv:Body><v1:CreateIngestTask><sessionId>' + uuid_login + '</sessionId><taskParameters><ing:uri>' + uri + '</ing:uri><ing:contentType>CompositionPlaylist</ing:contentType><ing:username></ing:username><ing:password></ing:password><ing:rawOptions></ing:rawOptions></taskParameters><taskProperties></taskProperties></v1:CreateIngestTask></soapenv:Body></soapenv:Envelope>';
            }
            if (api_type === 'get_task') {
                url = "http://" + address + ":" + port + "/dc/dcp/ws/v1/IngestManagement";
                body = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:v1="http://www.doremilabs.com/dc/dcp/ws/v1_0"><soapenv:Header/><soapenv:Body><v1:GetIngestTaskStatus><sessionId>' + uuid_login + '</sessionId><taskId>' + options_.task_id + '</taskId></v1:GetIngestTaskStatus></soapenv:Body></soapenv:Envelope>';
            }

        }

        let soapAction = '';

        if (type === 'AUDIOPROCESSOR') {

            if (api_type === 'get_certificates') {
                url = "http://" + address + ":" + port + "/cp/ws/smi/v1/services/SystemManagement";
                body = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:v1="http://www.dolby.com/cp/ws/smi/v1_1"><soapenv:Header/><soapenv:Body><v1:getCertificateRequest/></soapenv:Body></soapenv:Envelope>';
                soapAction = "http://www.dolby.com/cp/ws/smi/v1/getCertificate";
            }


            if (api_type === 'get_macros') {
                url = "http://" + address + ":" + port + "/cp/ws/smi/v1/services/SystemManagement";
                body = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:v1="http://www.dolby.com/cp/ws/smi/v1_0"><soapenv:Header/><soapenv:Body><v1:listMacrosRequest/></soapenv:Body></soapenv:Envelope>';
                soapAction = "http://www.dolby.com/cp/ws/smi/v1/listMacros";
            }

        }

        if (url === "" || body === "") {
            return resolve(undefined);
        }

        const options = {

            baseURL: url,
            method: 'POST',
            timeout: 10000,
            headers: {
                "Accept-Encoding": "gzip,deflate",
                "Content-Type": "text/xml;charset=UTF-8",
                'SOAPAction': soapAction,
                'Connection': 'Keep-Alive',

            },
            auth: {},
            httpsAgent: agent,

            data: body,

        }

        //console.log(body);

        axios(options).then(res => {

            return resolve(res.data);

        }).catch(error => {

            //console.log(error);
            return resolve(undefined);

        });


    });


}

exports.soapAPI = soapAPI;
exports.soapLogin = soapLogin;