[{* Smarty template for JDisc import
    @ author: Benjamin Heisig <bheisig@i-doit.org>
    @ author: Leonard Fischer <lfischer@i-doit.org>
    @ copyright: synetics GmbH
    @ license: <http://www.i-doit.com/license>
*}]

<div id="module-jdisc-import">
    <ul id="objectTabs" class="m0 gradient browser-tabs">
        <li><a href="#import" data-tab="#import">[{isys type="lang" ident=LC__MODULE__JDISC__IMPORT}]</a></li>
        [{if isset($discovery_tpl)}]
        <li><a href="#discovery" data-tab="#discovery">[{isys type="lang" ident=LC__MODULE__JDISC__DISCOVERY}]</a></li>
        [{/if}]
    </ul>

    <div id="import">
        <h3 class="border-top border-bottom bg-neutral-200 p5 mt10">
            [{isys type='lang' ident='LC__MODULE__JDISC__IMPORT__OPTIONS'}]

            <span class="fr">
                <a href="[{$link_to_jdisc_configuration}]" title="[{isys type='lang' ident='LC__MODULE__JDISC__CONFIGURATION'}]">[{isys type='lang' ident='LC__MODULE__JDISC__LINK_TO_CONFIGURATION'}]</a> -
                <a href="[{$link_to_jdisc_profiles}]" title="[{isys type='lang' ident='LC__MODULE__JDISC__PROFILES'}]">[{isys type='lang' ident='LC__MODULE__JDISC__LINK_TO_PROFILES'}]</a>
            </span>
        </h3>
        <table class="contentTable" style="border-top: none;">
            <tr>
                <td class="key">[{isys type='f_label' name='C__MODULE__JDISC__IMPORT__JDISC_SERVERS' ident='LC__MODULE__JDISC__IMPORT__JDISC_SERVERS'}]</td>
                <td class="value">
                    [{isys type="f_dialog" name="C__MODULE__JDISC__IMPORT__JDISC_SERVERS" p_bDbFieldNN=1 p_bSort=false p_strClass="normal"}]
                    <img src="[{$dir_images}]ajax-loading.gif" id="switch-server-loader" class="vam hide">
                </td>
            </tr>

            <tr id="jdisc_groups" style="[{if $jedi_version}]display:none;[{/if}]">
                <td class="key">[{isys type='f_label' name='C__MODULE__JDISC__IMPORT__GROUP' ident='LC__MODULE__JDISC__IMPORT__GROUP'}]</td>
                <td class="value">
                    [{isys type="f_dialog" name="C__MODULE__JDISC__IMPORT__GROUP" p_strClass="normal" p_bSort=false}]
                </td>
            </tr>

            [{if count($filter_files) > 0}]
                <tr>
                    <td class="key">
                        [{isys type='f_label' name='C__MODULE__JDISC__IMPORT__FILTER' ident='LC_UNIVERSAL__FILTERS'}]
                    </td>
                    <td class="value">
                        [{isys type="f_dialog" name="C__MODULE__JDISC__IMPORT__FILTER" p_strClass="normal" p_bSort=false}]
                    </td>
                </tr>
                [{foreach from=$filter_files item='filter_file'}]
                    [{include file=$filter_file}]
                [{/foreach}]
            [{/if}]
            <tr>
                <td class="key">[{isys type='f_label' name='C__MODULE__JDISC__IMPORT__PROFILE' ident='LC__MODULE__JDISC__IMPORT__PROFILE' mandatory=true}]</td>
                <td class="value">
                    [{isys type="f_dialog" name="C__MODULE__JDISC__IMPORT__PROFILE" p_strClass="normal" p_bDbFieldNN=true}]
                </td>
            </tr>
            <tr>
                <td class="key vat">[{isys type='f_label' name='C__MODULE__JDISC__IMPORT__MODE' ident='LC__MODULE__JDISC__IMPORT__MODE' mandatory=true}]</td>
                <td>
                    [{isys type="f_dialog" name="C__MODULE__JDISC__IMPORT__MODE" p_strClass="normal" p_bDbFieldNN=true}]
                    <br class="cb" />
                    <dl class="ml20 mt10">
                        <dt class="text-bold">[{isys type='lang' ident='LC__MODULE__JDISC__IMPORT__MODE'}]:</dt>
                        <dd style="margin-left: 2em;">[{isys type='lang' p_bHtmlEncode="0" ident='LC__MODULE__JDISC__IMPORT__MODE__DESCRIPTION'}]</dd>
                    </dl>
                </td>
            </tr>
            [{if !$ip_unique_check}]
            <tr>
                <td class="key">[{isys type="f_label" name="C__MODULE__JDISC__IMPORT__IP_CONFLICTS" ident="LC__MODULE__JDISC__IMPORT__OVERWRITE_IP_CONFLICTS"}]</td>
                <td class="value">
                    [{isys type="f_dialog" name="C__MODULE__JDISC__IMPORT__IP_CONFLICTS" p_strClass="normal" p_bDisabled=$ip_unique_check p_bDbFieldNN=true}]
                </td>
            </tr>
            [{/if}]
            <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">
                        <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"><label for="module-jdisc-import-detailed-logging">[{isys type="lang" ident="LC__MODULE__JDISC__IMPORT__CREATE_SEARCH_INDEX"}]</label></td>
                <td class="value pl20"><input type="checkbox" checked="checked" id="C__MODULE__JDISC__IMPORT__CREATE_SEARCH_INDEX" name="C__MODULE__JDISC__IMPORT__CREATE_SEARCH_INDEX"></td>
            </tr>
            <tr>
                <td></td>
                <td>
                    <div class="ml20">
                        <p>
                            [{$form_description}]
                        </p>
                        <a href="#" class="jdisc-import__form-description__link" id="jdisc-import__form-description__link">[{isys type="lang" ident="LC__MODULE__JDISC__IMPORT__FORM_DESCRIPTION__LINK"}]</a>
                        <div class="jdisc-import__form-description__text hide" id="jdisc-import__form-description__text">
                            <div class="description__text">
                                <h2 class="header">[{isys type="lang" ident="LC__MODULE__JDISC__IMPORT__FORM_DESCRIPTION__HEADER"}]</h2>
                                <dl>
                                    <dt>[{isys type="lang" ident="LC__UNIVERSAL__BUTTON_PAUSE"}]:</dt>
                                    <dd>[{isys type="lang" ident="LC__MODULE__JDISC__IMPORT__FORM_DESCRIPTION__PAUSE"}]</dd>
                                    <dt>[{isys type="lang" ident="LC__UNIVERSAL__BUTTON_CONTINUE"}]:</dt>
                                    <dd>[{isys type="lang" ident="LC__MODULE__JDISC__IMPORT__FORM_DESCRIPTION__CONTINUE"}]</dd>
                                    <dt>[{isys type="lang" ident="LC__UNIVERSAL__BUTTON_CANCEL"}]:</dt>
                                    <dd>[{isys type="lang" ident="LC__MODULE__JDISC__IMPORT__FORM_DESCRIPTION__CANCEL"}]</dd>
                                </dl>
                            </div>
                        </div>
                    </div>
                </td>
            </tr>
            <tr>
                <td></td>
                <td>
                    <button type="button" name="import" id="C__MODULE__JDISC__IMPORT__BUTTON" class="ml20 btn">[{isys type='lang' ident='LC__MODULE__JDISC__START_IMPORT'}]</button>
                    <button type="button" name="import" id="C__MODULE__JDISC__IMPORT__CANCEL_BUTTON" class="ml20 btn" disabled>[{isys type='lang' ident='LC__UNIVERSAL__BUTTON_CANCEL'}]</button>
                    <span class="import-status ml10 hide">[{isys type="lang" ident="LC__UNIVERSAL__IMPORT_IN_PROGRESS"}]</span>
                </td>
            </tr>
        </table>

        <div id="module-jdisc-import-message" class="m10 p5 hide"></div>

        <input type="hidden" id="module-jdisc-import-filter-type" value="">
        <input type="hidden" id="module-jdisc-import-filter-data" value="">

        <fieldset class="overview">
            <legend>
                <span>[{isys type='lang' ident='LC__MODULE__JDISC__IMPORT__RESULT'}]</span>
            </legend>
            <div id="module-jdisc-import-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>
    </div>
    [{if isset($discovery_tpl)}]
    <div id="discovery">
        [{include file=$discovery_tpl}]
    </div>
    [{/if}]


    <script type="text/javascript">

        [{if !$is_connected}]
            $('C__MODULE__JDISC__IMPORT__BUTTON').addClassName('disabled');
            document.observe('dom:loaded', function(){
               idoit.Notify.error('[{$error}]');
            });
        [{/if}]

        (function () {
            "use strict";

            let queue = '';
            let intervalId;

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

            $('C__MODULE__JDISC__IMPORT__CANCEL_BUTTON').on('click', function () {
                new Ajax.Request(`?call=jdisc&ajax=1&func=pause&queue=${queue}`);

                if (confirm("[{isys type='lang' p_bHtmlEncode=false ident='LC__MODULE__JDISC__IMPORT__CANCEL_CONFIRMATION'}]")) {
                    new Ajax.Request(`?call=jdisc&ajax=1&func=cancel&queue=${queue}`);
                    clearInterval(intervalId);
                } else {
                    new Ajax.Request(`?call=jdisc&ajax=1&func=continue&queue=${queue}`);
                    clearInterval(intervalId);
                }
            });

            $('C__MODULE__JDISC__IMPORT__BUTTON').on('click', function () {
                if (this.hasClassName('disabled')) return;

                if (this.hasClassName('processing')) {
                    const btn = this;
                    btn.disable();
                    new Ajax.Request(`?call=jdisc&ajax=1&func=pause&queue=${queue}`, {
                        onComplete: function () {
                            btn
                                .update("[{isys type='lang' ident='LC__UNIVERSAL__BUTTON_CONTINUE'}]")
                                .removeClassName('processing')
                                .addClassName('paused')
                                .enable();

                            btn.next('span.import-status')
                                .update("[{isys type='lang' ident='LC__UNIVERSAL__BUTTON_PAUSE'}]");

                            clearInterval(intervalId);
                        }
                    });
                    return;
                }

                if (this.hasClassName('paused')) {
                    const btn = this;
                    btn.disable();
                    new Ajax.Request(`?call=jdisc&ajax=1&func=continue&queue=${queue}`, {
                        onComplete: function () {
                            btn
                                .update("[{isys type='lang' ident='LC__UNIVERSAL__BUTTON_PAUSE'}]")
                                .removeClassName('paused')
                                .addClassName('processing')
                                .enable();

                            btn.next('span.import-status')
                                .update('[{isys type="lang" ident="LC__UNIVERSAL__IMPORT_IN_PROGRESS"}]');
                            clearInterval(intervalId);
                        }
                    });
                    return;
                }

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

                this
                    .update("[{isys type='lang' ident='LC__UNIVERSAL__BUTTON_PAUSE'}]")
                    .addClassName('processing');

                this.next('span.import-status')
                    .update('[{isys type="lang" ident="LC__UNIVERSAL__IMPORT_IN_PROGRESS"}]')
                    .removeClassName('hide');

                $('C__MODULE__JDISC__IMPORT__CANCEL_BUTTON').enable();

                queue = createQueueId();

                const parameters = {
                    queue: queue,
                    jdisc_server: $('C__MODULE__JDISC__IMPORT__JDISC_SERVERS').value,
                    group: (($('C__MODULE__JDISC__IMPORT__GROUP'))? $('C__MODULE__JDISC__IMPORT__GROUP').value: '-1'),
                    profile: $('C__MODULE__JDISC__IMPORT__PROFILE').value,
                    mode: $('C__MODULE__JDISC__IMPORT__MODE').value,
                    filter_type: $('module-jdisc-import-filter-type').value,
                    filter_data: $('module-jdisc-import-filter-data').value,
                    'detailed-logging': $('module-jdisc-import-detailed-logging').value,
                    'regenerate-index': ($('C__MODULE__JDISC__IMPORT__CREATE_SEARCH_INDEX').checked? 1: 0),
                    overwrite_hostaddress: (($('C__MODULE__JDISC__IMPORT__IP_CONFLICTS'))? $('C__MODULE__JDISC__IMPORT__IP_CONFLICTS').value: 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) => {
                    let log_message = [],
                        log,
                        i,
                        error_msg = '';

                    try {
                        const evtData = JSON.parse(event.data.trim());
                        switch (evtData.type) {
                            // import progress
                            case 'progress':
                                if (!$(`jdisc-import-progress-${evtData.id}`)) {
                                    log_container.insert(`
                                        <div class="progress-wrapper" id="jdisc-import-progress-${evtData.id}" style="padding:5px 0;">
                                            <div class="progress">
                                                <div class="progress-bar" style="width:${evtData.progress}%;"></div>
                                            </div>
                                            <div class="progress-legend"style=" padding:5px 0;">${evtData.message}</div>
                                        </div>
                                    `);
                                } else {
                                    // update the progress bar
                                    $$(`#jdisc-import-progress-${evtData.id} .progress-bar`)[0]
                                        .style.width = `${evtData.progress}%`;
                                    // update the legend
                                    $$(`#jdisc-import-progress-${evtData.id} .progress-legend`)[0]
                                        .update(evtData.message);
                                }
                                break;

                            case 'log':
                                if (evtData.data) {
                                    evtData.message = evtData.data.stats;
                                }
                                log_container.insert(evtData.message + '<br>');
                                break;

                            case 'continue':
                                const btn = $('C__MODULE__JDISC__IMPORT__BUTTON');
                                btn
                                    .update("[{isys type='lang' ident='LC__UNIVERSAL__BUTTON_PAUSE'}]")
                                    .removeClassName('paused')
                                    .addClassName('processing');

                                btn.next('span.import-status')
                                    .update('[{isys type="lang" ident="LC__UNIVERSAL__IMPORT_IN_PROGRESS"}]');

                                clearInterval(intervalId);
                                break;

                            case 'pause':
                                const importStatus = $('C__MODULE__JDISC__IMPORT__BUTTON').next('span.import-status');
                                if (importStatus && evtData.time && evtData.actionMessage) {
                                    const targetTime = new Date(evtData.time * 1000).getTime();

                                    function updateCountdown() {
                                        const currentTime = new Date().getTime();
                                        const timeRemaining = targetTime - currentTime;

                                        if (timeRemaining <= 0) {
                                            clearInterval(intervalId);
                                        } else {
                                            const seconds = Math.floor(timeRemaining / 1000);
                                            const minutes = Math.floor(seconds / 60);
                                            const hours = Math.floor(minutes / 60);

                                            const paddedHours = String(hours).padStart(2, '0');
                                            const paddedMinutes = String(minutes % 60).padStart(2, '0');
                                            const paddedSeconds = String(seconds % 60).padStart(2, '0');

                                            importStatus.update(`${evtData.actionMessage}: ${paddedHours}:${paddedMinutes}:${paddedSeconds}`);
                                        }
                                    }

                                    intervalId = setInterval(updateCountdown, 1000);
                                }
                                break;

                            case 'error':
                                [{if isset($dirs.log)}]
                                    error_msg = '[{isys type="lang" ident="LC__MODULE__JDISC__IMPORT__REQUEST_ERROR" values=$dirs.log}]';
                                [{else}]
                                    error_msg = '[{isys type="lang" ident="LC__MODULE__JDISC__IMPORT__REQUEST_ERROR" values="/log"}]';
                                [{/if}]
                                message_container
                                    .addClassName('box-red')
                                    .removeClassName('hide')
                                    .update('[{isys type="lang" ident="LC__MODULE__JDISC__REQUEST_ERROR"}]');
                                log_container.update(error_msg + '<br />' + evtData.message).addClassName('box-red mt15 m10');

                                idoit.Notify.error(evtData.message);
                                log_container.update(evtData.message);

                                this
                                    .update('[{isys type='lang' ident='LC__MODULE__JDISC__START_IMPORT'}]')
                                    .removeClassName('processing');

                                this.next('span.import-status')
                                    .addClassName('hide');

                                $('C__MODULE__JDISC__IMPORT__CANCEL_BUTTON').disable();

                                evtSource.close();
                                clearInterval(intervalId);
                                break;

                            // close the connection if the import is finished
                            case 'end':
                                this
                                    .update('[{isys type='lang' ident='LC__MODULE__JDISC__START_IMPORT'}]')
                                    .removeClassName('processing')
                                    .removeClassName('paused');

                                this.next('span.import-status')
                                    .addClassName('hide');

                                message_container
                                        .addClassName(evtData.message ? 'box-yellow' : 'box-green')
                                        .removeClassName('hide')
                                        .update(evtData.message ? evtData.message : "[{isys type='lang' ident='LC__MODULE__JDISC__IMPORT__SUCCEEDED'}]");

                                $('C__MODULE__JDISC__IMPORT__CANCEL_BUTTON').disable();

                                evtSource.close();
                                clearInterval(intervalId);
                                break;

                            default:
                                evtSource.close();
                                clearInterval(intervalId);
                        }
                    } catch (e) {
                        evtSource.close();
                    }
                };
            });

            $('C__MODULE__JDISC__IMPORT__JDISC_SERVERS').on('change', function(ele) {
                $('switch-server-loader').removeClassName('hide');
                $('C__MODULE__JDISC__IMPORT__BUTTON').addClassName('disabled');

                new Ajax.Request('?call=jdisc&ajax=1&func=get_groups_and_profiles',
                    {
                        parameters: {
                            jdisc_server: ele.findElement().value
                        },
                        method: "post",
                        onComplete: function (transport) {
                            var json = transport.responseJSON;
                            $('switch-server-loader').addClassName('hide');

                            if(json && json.success)
                            {
                                $('C__MODULE__JDISC__IMPORT__BUTTON').removeClassName('disabled');
                                var jdisc_profiles = $H(json.data.profiles);
                                var groups_ele = $('C__MODULE__JDISC__IMPORT__GROUP');
                                var profiles_ele = $('C__MODULE__JDISC__IMPORT__PROFILE');
                                var show_jdisc_groups = false;

                                if(json.data.groups === false)
                                {
                                    if($('jdisc_groups').visible())
                                    {
                                        $('jdisc_groups').hide();
                                    }
                                }
                                else
                                {
                                    if(!$('jdisc_groups').visible())
                                    {
                                        $('jdisc_groups').show();
                                    }
                                    show_jdisc_groups = true;
                                    var jdisc_groups = $H(json.data.groups);
                                }

                                if(show_jdisc_groups)
                                {
                                    if(groups_ele)
                                    {
                                        var cloned_first_element = groups_ele.options[0].cloneNode();
                                        groups_ele.update(cloned_first_element);

                                        jdisc_groups.each(function(ele){
                                            groups_ele.insert(new Element('option', {value:ele.key}).insert(ele.value));
                                        });
                                    }
                                    groups_ele.removeAttribute('disabled');
                                }
                                else
                                {
                                    groups_ele.setAttribute('disabled', 'disabled');
                                }

                                profiles_ele.update('');

                                jdisc_profiles.each(function(ele) {
                                    // check if value is not a function (case for empty profiles)
                                    if (typeof ele.value !== 'function') {
                                        profiles_ele.insert(new Element('option', {value:ele.key}).insert(ele.value));
                                    }
                                });
                                if($('C__MODULE__JDISC__IMPORT__BUTTON').hasClassName('disabled'))
                                {
                                    $('C__MODULE__JDISC__IMPORT__BUTTON').removeClassName('disabled');
                                }
                            } else {
                                idoit.Notify.error(json.message);

                                if(!$('C__MODULE__JDISC__IMPORT__BUTTON').hasClassName('disabled'))
                                {
                                    $('C__MODULE__JDISC__IMPORT__BUTTON').addClassName('disabled');
                                }
                            }
                        }
                    }
                );
            });

            if ($('C__MODULE__JDISC__IMPORT__FILTER')) {
                $('C__MODULE__JDISC__IMPORT__FILTER').on('change', function (ele) {
                    var l_id = ele.findElement().value;

                    $$('.import_filter').each(function (ele) {
                        ele.hide();
                    });
                    $$(' .' + l_id).each(function (ele) {
                        ele.show();
                    });

                    $('module-jdisc-import-filter-type').value = l_id;
                });
            }

            new Tip(
                $('jdisc-import__form-description__link'),
                $('jdisc-import__form-description__text').innerHTML,
                {
                    className: 'objectinfo'
                }
            );
        }());
    </script>
</div>
<script type="text/javascript">
    new Tabs('objectTabs', {
        wrapperClass: 'browser-tabs',
        contentClass: 'browser-tab-content',
        tabClass:     'mouse-pointer'
    });
</script>

<style type="text/css">
#C__MODULE__JDISC__IMPORT__BUTTON.paused::before,
#C__MODULE__JDISC__IMPORT__BUTTON.processing::before {
    display: inline-block;

    width: 16px;
    height: 16px;
    margin-right: 4px;

    content: '';

    background-image: url('[{$dir_images}]axialis/basic/symbol-update.svg');
    background-size: cover;
}
#C__MODULE__JDISC__IMPORT__BUTTON.processing::before {
    animation: 1s linear infinite rotate360;
}
.objectinfo .description__text dl {
    padding: 5px;
}
.objectinfo .description__text dl dt {
    font-weight: bold;
}
.objectinfo .description__text dl dd {
    padding-bottom: 5px;
}
.jdisc-import__form-description__link::before {
    position: relative;
    top: 4px;

    display: inline-block;

    width: 16px;
    height: 16px;
    margin-right: 4px;

    content: '';

    background-image: url('[{$dir_images}]axialis/basic/button-info.svg');
    background-size: cover;
}
.jdisc-import__form-description__link {
    padding: 8px 0;

    color: #0964b0;
}
</style>
