<div>
    <table class="contentTable">
        <tr>
            <td class="key">[{isys type='f_label' name='C__CMDB__CATG__JDISC_DISCOVERY__SERVER' ident='LC__CMDB__CATG__JDISC_DISCOVERY__JDISC_SERVER'}]</td>
            <td class="value">
                [{isys type='f_dialog' p_bDbFieldNN=1 name='C__CMDB__CATG__JDISC_DISCOVERY__SERVER' p_bEditMode=1}]
            </td>
        </tr>

        <tr>
            <td class="key">[{isys type='f_label' name='C__CMDB__CATG__JDISC_DISCOVERY__PROFILE' ident='LC__CMDB__CATG__JDISC_DISCOVERY__JDISC_PROFILE' description="LC__CMDB__CATG__JDISC_DISCOVERY__JDISC_PROFILE__DESCRIPTION"}]</td>
            <td class="value">
                [{isys type='f_dialog' name='C__CMDB__CATG__JDISC_DISCOVERY__PROFILE' p_bEditMode=1}]
            </td>
        </tr>

        [{if !$ip_unique_check}]
        <tr>
            <td class="key">[{isys type="f_label" name="C__CMDB__CATG__JDISC_DISCOVERY__IP_CONFLICTS" ident="LC__MODULE__JDISC__IMPORT__OVERWRITE_IP_CONFLICTS"}]</td>
            <td class="value">
                [{isys type="f_dialog" name="C__CMDB__CATG__JDISC_DISCOVERY__IP_CONFLICTS" p_bEditMode=1 p_bDisabled=$ip_unique_check p_bDbFieldNN=true}]
            </td>
        </tr>
        [{/if}]

        <tr>
            <td class="key">[{isys type='f_label' name='C__CMDB__CATG__JDISC_DISCOVERY__MODE' ident='LC__CMDB__CATG__JDISC_DISCOVERY__UPDATE_MODE'}]</td>
            <td>
                [{isys type="f_dialog" name="C__CMDB__CATG__JDISC_DISCOVERY__MODE" p_bEditMode=1 p_bDbFieldNN=true}]
            </td>
        </tr>

        <tr>
            <td class="key">[{isys type='f_label' name='C__CMDB__CATG__JDISC_DISCOVERY__TARGET_TYPE' description="LC__CMDB__CATG__JDISC_DISCOVERY__TARGET_TYPE__DESCRIPTION" ident='LC__CMDB__CATG__JDISC_DISCOVERY__TARGET_TYPE'}]</td>
            <td>
                [{isys type="f_dialog" name="C__CMDB__CATG__JDISC_DISCOVERY__TARGET_TYPE" p_bEditMode=1 p_bDbFieldNN=true}]
            </td>
        </tr>

        <tr>
            <td class="key"><label for="module-jdisc-import-detailed-logging">[{isys type="lang" ident="LC__MODULE__JDISC__IMPORT__LOGGING"}]</label></td>
            <td class="value pl20">
                <select name="" id="module-jdisc-import-detailed-logging" class="input input-small">
                    <option value="0" selected="selected">[{isys type="lang" ident="LC__MODULE__JDISC__IMPORT__LOGGING_LESS"}]</option>
                    <option value="1">[{isys type="lang" ident="LC__MODULE__JDISC__IMPORT__LOGGING_DETAIL"}]</option>
                    <option value="2">[{isys type="lang" ident="LC__MODULE__JDISC__IMPORT__LOGGING_DEBUG"}]</option>
                </select>
            </td>
        </tr>

        <tr>
            <td class="key">

            </td>
            <td class="value jdisc-discovery pl20">
                <button type="button" class="btn" id="jdisc-discovery-scan">[{isys type="lang" ident="LC__CMDB__CATG__JDISC_DISCOVERY__SCAN"}]</button>
                <button type="button" class="btn" id="jdisc-discovery-update">[{isys type="lang" ident="LC__CMDB__CATG__JDISC_DISCOVERY__UPDATE_OBJECT"}]</button>
                <button type="button" class="btn" id="jdisc-discovery-scan-update">[{isys type="lang" ident="LC__CMDB__CATG__JDISC_DISCOVERY__SCAN_UPDATE_OBJECT"}]</button>
                <span class="ml10 hide" id="jdisc-discovery-progress-text">[{isys type="lang" ident="LC__UNIVERSAL__IMPORT_IN_PROGRESS"}]</span>
            </td>
        </tr>
    </table>
    <div id="module-jdisc-import-message" class="m10 p5 hide"></div>
    <fieldset class="overview hide" id="jdisc-discovery-import-container">
        <legend>
            <span>
                [{isys type="lang" ident="LC__CMDB__CATG__JDISC_DISCOVERY__IMPORT_RESULT"}]
                <img src="[{$dir_images}]ajax-loading.gif" id="jdisc-discovery-import-container-loader" class="ml5 vam hide">
            </span>
        </legend>
        <div id="jdisc-discovery-import-container-log" class="mt5 p10" style="border-top: none; font-family: 'Lucida Console','Monaco',Courier New, monospace;">
            [{isys type="lang" ident="LC__UNIVERSAL__WAITING"}]
        </div>
    </fieldset>
    <fieldset class="overview hide" id="jdisc-discovery-scan-container">
        <legend>
            <span>
                [{isys type="lang" ident="LC__CMDB__CATG__JDISC_DISCOVERY__DISCOVERY_LOG"}]
                <img src="[{$dir_images}]ajax-loading.gif" id="jdisc-discovery-scan-container-loader" class="ml5 vam hide">
                <button type="button" class="btn hide" id="jdisc-discovery-scan-container-cancel">Cancel Scan</button>
            </span>
        </legend>
        <div id="jdisc-discovery-scan-container-log" class="mt5 p10" style="border-top: none">
            [{isys type="lang" ident="LC__UNIVERSAL__WAITING"}]
        </div>
    </fieldset>

    <input type="hidden" id="C__MODULE__JDISC__IMPORT__FILTER__SERIAL_NUMBER" value="[{$serial_number}]">
    <input type="hidden" id="C__MODULE__JDISC__IMPORT__FILTER__ADDRESS" value="[{$primary_ip}]">
    <input type="hidden" id="C__MODULE__JDISC__IMPORT__FILTER__HOSTNAME" value="[{$primary_hostname}]">
    <input type="hidden" id="C__MODULE__JDISC__IMPORT__OBJECT_ID" value="[{$object_id}]">
    <input type="hidden" id="C__MODULE__JDISC__IMPORT__OBJECTTYPE_ID" value="[{$objectTypeID}]">

</div>
<script>
    (function () {
        "use strict";

        if($('C__CMDB__CATG__JDISC_DISCOVERY__SERVER')) {
            var scan_update = false;
	        var web_service_active = false;
	        // Ajax request for jdisc scan
            var req = null;

            function printMessage(message, type = 'success') {
                const messageClass     = type == 'success' ? 'box-green' : 'box-red';
                const messageContainer = $('module-jdisc-import-message');
                messageContainer
                    // reset
                    .removeClassName('box-red')
                    .removeClassName('box-green')
                    // set new
                    .addClassName(messageClass)
                    .removeClassName('hide')
                    .update(message);
            }

            function disableElement(element) {
                element.addClassName('disabled').setAttribute('disabled', 'disabled');
            }

            function enableElement(element) {
                element.removeClassName('disabled').removeAttribute('disabled');
            }

            function handleJDiscDiscoveryButtons(disableAll = false) {
                const scanBtn       = $('jdisc-discovery-scan'),
                      updateBtn     = $('jdisc-discovery-update'),
                      scanUpdateBtn = $('jdisc-discovery-scan-update');

                // reset
                enableElement(scanBtn);
                enableElement(updateBtn);
                enableElement(scanUpdateBtn);

                // disable all
                if (disableAll) {
                    disableElement(scanBtn);
                    disableElement(updateBtn);
                    disableElement(scanUpdateBtn);
                    return;
                }

                const scanAvailable   = isScanAvailable(),
                      updateAvailable = isUpdateAvailable();

                // disable some
                if (!scanAvailable) {
                    disableElement(scanBtn);
                }
                if (!updateAvailable) {
                    disableElement(updateBtn);
                }
                if (!scanAvailable || !updateAvailable) {
                    disableElement(scanUpdateBtn);
                }
            }

            function handleJDiscDiscoveryOptions(disableAll = false) {
                const profileOption = $('C__CMDB__CATG__JDISC_DISCOVERY__PROFILE'),
                      targetOption  = $('C__CMDB__CATG__JDISC_DISCOVERY__TARGET_TYPE'),
                      serverOption  = $('C__CMDB__CATG__JDISC_DISCOVERY__SERVER');

                // reset
                enableElement(profileOption);
                enableElement(targetOption);
                enableElement(serverOption);


                // disable all
                if (disableAll) {
                    disableElement(profileOption);
                    disableElement(targetOption);
                    disableElement(serverOption);
                }
            }

            function isUpdateAvailable() {
                return $('C__CMDB__CATG__JDISC_DISCOVERY__PROFILE').getValue() > 0 && web_service_active;
            }

            function isScanAvailable() {
                return handleJdiscImportFilterData() && web_service_active;
            }

            var getJdiscData = function (jdisc_server) {
                new Ajax.Request('?call=jdisc&ajax=1&func=get_groups_and_profiles',
                    {
                        parameters: {
                            'jdisc_server': jdisc_server,
                            'object_type': $('C__MODULE__JDISC__IMPORT__OBJECTTYPE_ID').getValue(),
                            'check_web_service': 1
                        },
                        method: "post",
                        onSuccess: function (transport) {
                            var json = transport.responseJSON;
                            web_service_active = false;

                            const profiles_ele = $('C__CMDB__CATG__JDISC_DISCOVERY__PROFILE');
                            profiles_ele.update('');
                            profiles_ele.insert(new Element('option', {value:'-1'}).insert('-'));

                            if (json && json.success) {
                                var jdisc_profiles = $H(json.data.profiles);
                                var default_profile = json.data.default_profile;
                                web_service_active = json.data.web_service_active;

                                const $targetTypeSelect   = $('C__CMDB__CATG__JDISC_DISCOVERY__TARGET_TYPE'),
                                      $serialNumberOption = $targetTypeSelect.down('option[value="serialnumber"]');
                                if (json.data.graphql_active) {
                                    $serialNumberOption.show();
                                } else {
                                    $serialNumberOption.hide();
                                    if ($targetTypeSelect.getValue() === 'serialnumber') {
                                        $targetTypeSelect.setValue('ip');
                                    }
                                }

                                jdisc_profiles.each(function (ele) {
                                    if(ele.key === default_profile)
                                    {
                                        profiles_ele.insert(new Element('option', {'value':ele.key, 'selected':true, 'class':'bold'}).insert(ele.value + " ([{isys type='lang' ident='LC__CMDB__CATG__JDISC_DISCOVERY__DEFAULT_PROFILE'}])"));
                                    }
                                    else
                                    {
                                        if (typeof ele.value !== 'function') {
                                            profiles_ele.insert(new Element('option', {value:ele.key}).insert(ele.value));
                                        }
                                    }
                                });

                                handleJDiscDiscoveryButtons();
                                handleJDiscDiscoveryOptions();
                                if(!web_service_active)
                                {
                                    window.idoit.Notify.error('[{isys type="lang" ident="LC__MODULE__JDISC__DISCOVERY__CONNECTION_FAILED"}]')
                                }
                            }
                            else {
                                enableElement($('C__CMDB__CATG__JDISC_DISCOVERY__SERVER'));
                                if (json && json.message) {
                                    window.idoit.Notify.error(json.message);
                                } else {
                                    window.idoit.Notify.error('[{isys type="lang" ident="LC__MODULE__JDISC__DISCOVERY__CONNECTION_FAILED"}]');
                                }
                            }
                        }
                    }
                );
            }

            var handleJdiscImportFilterData = function () {
                const selectedIdentificationType = $('C__CMDB__CATG__JDISC_DISCOVERY__TARGET_TYPE').getValue();
                if (selectedIdentificationType == 'fqdn' && ($('C__MODULE__JDISC__IMPORT__FILTER__HOSTNAME').getValue() == '' || $('C__MODULE__JDISC__IMPORT__FILTER__HOSTNAME').getValue() == '-')) {
                    printMessage('[{isys type="lang" ident="LC__CMDB__CATG__JDISC_DISCOVERY__TARGET_TYPE__ERROR_NO_FQDN_SET"}]', 'error');
                    return false;
                }
                else if (selectedIdentificationType == 'ip' && $('C__MODULE__JDISC__IMPORT__FILTER__ADDRESS').getValue() == '') {
                    printMessage('[{isys type="lang" ident="LC__CMDB__CATG__JDISC_DISCOVERY__NO_PRIMARY_IP_ADDRESS_DEFINED"}]', 'error');
                    return false;
                }
                else if (selectedIdentificationType == 'serialnumber' && $('C__MODULE__JDISC__IMPORT__FILTER__SERIAL_NUMBER').getValue() == '') {
                    printMessage('[{isys type="lang" ident="LC__CMDB__CATG__JDISC_DISCOVERY__NO_SERIAL_NUMBER_DEFINED"}]', 'error');
                    return false;
                }
                return true;
            }

            $('C__CMDB__CATG__JDISC_DISCOVERY__TARGET_TYPE').on('change', function (ele) {
                $('module-jdisc-import-message').addClassName('hide');
                handleJDiscDiscoveryButtons();
            });

            $('C__CMDB__CATG__JDISC_DISCOVERY__PROFILE').on('change', function (ele) {
                handleJDiscDiscoveryButtons();
            });

            /*
             * Switch groups and profiles for the selected jdisc server
             */
            $('C__CMDB__CATG__JDISC_DISCOVERY__SERVER').on('change', function (ele) {
                const disableAll = true;
                handleJDiscDiscoveryButtons(disableAll);
                handleJDiscDiscoveryOptions(disableAll);
                $('module-jdisc-import-message').addClassName('hide');
                getJdiscData($('C__CMDB__CATG__JDISC_DISCOVERY__SERVER').getValue());
            });

            /*
             * Import device to i-doit
             */
            $('jdisc-discovery-update').on('click', function(){

                if(this.hasClassName('disabled')) return;

                $('jdisc-discovery-progress-text').removeClassName('hide');

                const disableAll = true;
                handleJDiscDiscoveryButtons(disableAll);
                handleJDiscDiscoveryOptions(disableAll);
                start_jdisc_import();
            });

            var start_jdisc_import = function() {
                $('jdisc-discovery-import-container-loader').removeClassName('hide');
                $('jdisc-discovery-import-container').removeClassName('hide');

                var message_container = $('module-jdisc-import-message').update().removeClassName('box-red').removeClassName('box-green'),
                        log_container = $('jdisc-discovery-import-container-log').update('[{isys type='lang' ident='LC__UNIVERSAL__LOADING'}]');

                const queue = createQueueId();

                const parameters = {
                    'queue': queue,
                    'jdisc_server': $('C__CMDB__CATG__JDISC_DISCOVERY__SERVER').getValue(),
                    'group': '-1',
                    'profile': $('C__CMDB__CATG__JDISC_DISCOVERY__PROFILE').getValue(),
                    'mode': $('C__CMDB__CATG__JDISC_DISCOVERY__MODE').getValue(),
                    'objID': '[{$smarty.get.objID|strip_tags|escape}]',
                    'objTypeID': '[{$smarty.get.objTypeID|strip_tags|escape}]',
                    'detailed-logging': $('module-jdisc-import-detailed-logging').getValue(),
                    'overwrite_hostaddress': (($('C__CMDB__CATG__JDISC_DISCOVERY__IP_CONFLICTS'))? $('C__CMDB__CATG__JDISC_DISCOVERY__IP_CONFLICTS').getValue(): 0)
                };

                const keys = Object.keys(parameters);
                let parametersArray = [];
                for (let i = 0; i < keys.length; i++) {
                  parametersArray.push(`${keys[i]}=${encodeURIComponent(parameters[keys[i]])}`);
                }

                const evtSource = new EventSource(`${window.www_dir}?call=jdisc&ajax=1&func=import&${parametersArray.join('&')}`);
                evtSource.onmessage = (event) => {
                    try {
                        const evtData = JSON.parse(event.data.trim());
                        switch (evtData.type) {
                            // display the import progress
                            case 'progress':
                            case 'log':
                                if (evtData.data) {
                                    evtData.message = evtData.data.stats;
                                }
                                log_container.insert(evtData.message + '<br>');
                                break;
                            case 'error':
                                printMessage('[{isys type="lang" ident="LC__MODULE__JDISC__REQUEST_ERROR"}]', 'error');
                                idoit.Notify.error(evtData.message);
                                evtSource.close();
                                enableImportBtn();
                                break;
                            // close the connection if the import is finished
                            case 'end':
                                idoit.Notify.success("[{isys type='lang' ident='LC__MODULE__JDISC__IMPORT__SUCCEEDED'}]");
                                printMessage("[{isys type='lang' ident='LC__MODULE__JDISC__IMPORT__SUCCEEDED'}]");
                            default:
                                evtSource.close();
                                enableImportBtn();
                                break;
                        }
                    } catch (e) {
                        evtSource.close();
                        enableImportBtn();
                    }
                };

                function enableImportBtn() {
                    $('jdisc-discovery-import-container-loader').addClassName('hide');
                    handleJDiscDiscoveryButtons();
                    handleJDiscDiscoveryOptions();
                    $('jdisc-discovery-progress-text').addClassName('hide');
                }

                function createQueueId() {
                    const prefix = 'jdisc_import';
                    const timestamp = new Date().getTime();
                    const random = Math.random().toString(36).substring(2, 15);
                    return `${prefix}_${timestamp}_${random}`;
                }
            };

            /*
             * @todo
             * Does not work at the moment because there is no soap call for cancelling a jdisc scan of a device
             */
            $('jdisc-discovery-scan-container-cancel').on('click', function(){
                if(req)
                {
                    req.transport.abort();

                    handleJDiscDiscoveryButtons();
                    handleJDiscDiscoveryOptions();
                    //$('jdisc-discovery-scan-container-cancel').addClassName('hide');
                    $('jdisc-discovery-scan-container-loader').addClassName('hide');
                    req = null;
                }
            });

            /*
             * Scan device
             */
            $('jdisc-discovery-scan').on('click', function(){

                if(this.hasClassName('disabled')) return;

                $('jdisc-discovery-progress-text').removeClassName('hide');

                // Disable buttons while scanning
                const disableAll = true;
                handleJDiscDiscoveryButtons(disableAll);
                handleJDiscDiscoveryOptions(disableAll);
                // Start jdisc scan
                start_jdisc_scan();
            });

            var intervalTimer;

            var intervalFunc = function (req_params, timeout, retries){
                var timeoutValue = parseInt($('configuredTimeout').innerHTML);

                if (timeoutValue == 0) {
                    checkScanQueue(req_params, timeout, retries);
                } else {
                    timeoutValue = timeoutValue - 1;
                    $('configuredTimeout').innerHTML = timeoutValue;
                }
            }

            var startIntervalFunc = function (req_params, timeout, retries) {
                intervalTimer = setInterval(function (){
                    intervalFunc(req_params, timeout, retries);
                }, 1000);
            }

            var checkScanQueue = function (req_params, timeout, retries) {
                req_params[0].innerHTML += 'Check if device is still in the queue.<br />';
                clearInterval(intervalTimer);

                new Ajax.Request('?call=jdisc&ajax=1&func=checkQueue', {
                    method: "post",
                    parameters: {
                        'host': $('C__CMDB__CATG__JDISC_DISCOVERY__SERVER').getValue()
                    },
                    onSuccess: function (transport){
                        var json = transport.responseJSON;
                        var timeoutRetries = parseInt($('configuredRetries').innerHTML);

                        // Check if device is still in queue
                        if (json.success) {
                            req_params[0].innerHTML += 'Device is not in the queue anymore starting import.<br />';
                            start_jdisc_import();
                            return;
                        }

                        if (retries >= 1)
                        {
                            retries = parseInt(retries) - 1;

                            req_params[0].innerHTML += 'Device is in queue retries left ' + retries + '.<br />';
                            $('configuredTimeout').innerHTML = timeout;
                            $('configuredRetries').innerHTML = retries;

                            startIntervalFunc(req_params, timeout, retries);
                        } else {
                            req_params[0].innerHTML += 'Device is still in queue please try the jdisc import later.<br />';
                        }
                    }.bind(req_params)
                });
            }

            /**
             * Function to scan the device
             */
            var start_jdisc_scan = function() {
                $('jdisc-discovery-scan-container-loader').removeClassName('hide');
                $('jdisc-discovery-scan-container').removeClassName('hide');
                //$('jdisc-discovery-scan-container-cancel').removeClassName('hide');

                var d = $('jdisc-discovery-scan-container-log');
                var old_text = '';
                var req_params = [d, old_text, '', false];
                d.innerHTML = '';

                var req_url = '?call=jdisc&ajax=1&func=discover&type=discover_device';

                const processResponse = function(responseText) {
                    const newText  = responseText.substring(req_params[1].length).trim(),
                          lastLine = responseText.split("\n").pop().trim();

                    let log = newText;
                    if (lastLine && lastLine.isJSON()) {
                        log = newText.replace(lastLine, '').trim();
                        req_params[2] = lastLine;
                    }

                    if (log != null && log != 'null' && log != 'false' && !log.isJSON()) {
                        req_params[0].innerHTML += log.replaceAll("\n", '<br />') + '<br />';
                        req_params[1] = log;
                    }
                }

                req = new Ajax.Request(req_url,
                {
                    method: "post",
                    parameters:{
                        'objID': $('C__MODULE__JDISC__IMPORT__OBJECT_ID').getValue(),
                        'objTypeID': $('C__MODULE__JDISC__IMPORT__OBJECTTYPE_ID').getValue(),
                        'host': $('C__CMDB__CATG__JDISC_DISCOVERY__SERVER').getValue(),
                        'hostaddress': $('C__MODULE__JDISC__IMPORT__FILTER__ADDRESS').getValue(),
                        'hostname': $('C__MODULE__JDISC__IMPORT__FILTER__HOSTNAME').getValue(),
                        'targetType': $('C__CMDB__CATG__JDISC_DISCOVERY__TARGET_TYPE').getValue(),
                        'serialnumber': $('C__MODULE__JDISC__IMPORT__FILTER__SERIAL_NUMBER').getValue()
                    },
                    onComplete: function(transport){
                        if (req_params[2].blank()) {
                            processResponse(transport.responseText);
                        }

                        const json = req_params[2].isJSON() ? JSON.parse(req_params[2]) : {};

                        $('jdisc-discovery-scan-container-loader').addClassName('hide');
                        //$('jdisc-discovery-log-scan-cancel').addClassName('hide');

                        if(!scan_update) {
                            handleJDiscDiscoveryButtons();
                            handleJDiscDiscoveryOptions();
                            $('jdisc-discovery-progress-text').addClassName('hide');
                        }

                        if(json.success)
                        {
                            idoit.Notify.success(json.message, {life:5});
                            // Trigger import if the scan update button has been clicked
                            if(scan_update)
                            {
                                scan_update = false;

                                if (json.data) {
                                    var timeout = json.data['timeout'];
                                    var retries = json.data['retries'];

                                    req_params[0].innerHTML += 'Waiting for configured timeout <span id="configuredTimeout" class="bold">' +
                                                               timeout + '</span>/' + timeout +
                                                               '. Retries <span id="configuredRetries" class="bold">' + retries +'</span>/ ' + retries + '.<br />';

                                    startIntervalFunc(req_params, timeout, retries);
                                } else{
                                    start_jdisc_import();
                                }
                            }
                        }
                        else
                        {
                            idoit.Notify.error(json.message, {life:5});
                            handleJDiscDiscoveryButtons();
                            handleJDiscDiscoveryOptions();
                            $('jdisc-discovery-scan-container').addClassName('hide');
                            $('jdisc-discovery-progress-text').addClassName('hide');
                        }
                    },
                    onInteractive: function (transport) {
                        processResponse(transport.responseText);
                        req_params[3] = true;
                    }
                });
            };

            /*
             * Scan device and immediately import device from jdisc to i-doit
             */
            $('jdisc-discovery-scan-update').on('click', function(){
                if(this.hasClassName('disabled')) return;

                const disableAll = true;
                handleJDiscDiscoveryButtons(disableAll);
                handleJDiscDiscoveryOptions(disableAll);
                scan_update = true;
                $('jdisc-discovery-progress-text').removeClassName('hide');

                if(!$('module-jdisc-import-message').hasClassName('hide'))
                {
                    $('module-jdisc-import-message').addClassName('hide');
                    $('jdisc-discovery-import-container-log').update('[{isys type="lang" ident="LC__UNIVERSAL__WAITING"}]');
                }
                // Start JDisc scan
                start_jdisc_scan();
            });

            $('C__CMDB__CATG__JDISC_DISCOVERY__SERVER').simulate('change');
        }
    }());
</script>
