/****************************************************************************************
 * LiveZilla ChatStartpageClass.js
 *
 ***************************************************************************************/
function ChatStartpageClass() {
}

ChatStartpageClass.OnboardingElements = [];
ChatStartpageClass.OnboardingComplete = '111111';

ChatStartpageClass.HasAtlasCspLicense = function () {
    var license = DataEngine.atlasLicense;

    return !!(
        license &&
        license.schema === 'ATLAS-LICENSE-STATUS-V1' &&
        license.allowed === true &&
        (
            license.mode === 'ACTIVE' ||
            license.mode === 'GRACE'
        ) &&
        license.entitlements &&
        license.entitlements.CSP === true
    );
};

ChatStartpageClass.EscapeHtml = function (value) {
    return String(value)
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#039;');
};

ChatStartpageClass.GetModuleStatus = function (key) {
    var license = DataEngine.atlasLicense;

    return !!(
        ChatStartpageClass.HasAtlasCspLicense() &&
        license.entitlements &&
        license.entitlements[key] === true
    );
};

ChatStartpageClass.prototype.createStartPage = function (lz, ca, cr) {
    if (!ChatStartpageClass.HasAtlasCspLicense()) {
        $('#startpage-body').html('');
        $('#onboarding').html('');
        lzm_chatDisplay.startPageTabControlDoesExist = false;
        lzm_chatDisplay.startPageExists = false;
        return false;
    }

    var pages =
        this.createStartPagesArray(
            lz,
            Array.isArray(ca) ? ca : [],
            Array.isArray(cr) ? cr : []
        );

    if (pages.length <= 1) {
        $('#startpage-body').html(
            pages.length === 1
                ? pages[0].content
                : this.createSingleStartPage(lz, ca, cr)
        );

        lzm_chatDisplay.startPageTabControlDoesExist = false;
    }
    else {
        $('#startpage-body').html(
            '<div id="startpage-placeholder"></div>'
        );

        lzm_inputControls.createTabControl(
            'startpage-placeholder',
            pages,
            -1,
            lzm_chatDisplay.windowWidth - 22
        );

        lzm_chatDisplay.startPageTabControlDoesExist = true;
    }

    lzm_chatDisplay.startPageExists = true;

    ChatStartpageClass.ShowOnboarding();
    UIRenderer.resizeStartPage();

    $('#startpage-placeholder-tab')
        .off('click.atlasStartpage')
        .on('click.atlasStartpage', function () {
            UIRenderer.resizeStartPage();
        });

    return true;
};

ChatStartpageClass.prototype.createSingleStartPage = function () {
    if (!ChatStartpageClass.HasAtlasCspLicense()) {
        return '';
    }

    var license = DataEngine.atlasLicense;
    var operatorCapacity = 'Unavailable';

    if (
        license.entitlements.PRO === true &&
        license.operatorLimit === null
    ) {
        operatorCapacity = 'Unlimited';
    }
    else if (
        license.entitlements.PRO === true &&
        typeof license.operatorLimit === 'number' &&
        isFinite(license.operatorLimit) &&
        Math.floor(license.operatorLimit) ===
            license.operatorLimit &&
        license.operatorLimit > 0
    ) {
        operatorCapacity =
            String(license.operatorLimit);
    }

    var moduleCard = function (key, title) {
        var enabled =
            ChatStartpageClass.GetModuleStatus(key);

        return '<div style="' +
            'box-sizing:border-box;' +
            'display:inline-block;' +
            'vertical-align:top;' +
            'width:220px;' +
            'min-height:95px;' +
            'margin:6px;' +
            'padding:14px;' +
            'border:1px solid #dce4ea;' +
            'border-radius:6px;' +
            'background:#fff;' +
            'text-align:left;">' +
            '<div style="font-weight:bold;">' +
            ChatStartpageClass.EscapeHtml(title) +
            '</div>' +
            '<div class="' +
            (enabled ? 'text-green' : 'text-gray') +
            '" style="margin-top:12px;">' +
            (enabled ? 'Enabled' : 'Disabled') +
            '</div>' +
            '</div>';
    };

    var html =
        '<div id="atlas-startpage-dashboard" ' +
        'style="box-sizing:border-box;padding:24px;text-align:center;">' +

        '<div style="' +
        'max-width:980px;' +
        'margin:0 auto;' +
        'padding:24px;' +
        'border:1px solid #dce4ea;' +
        'border-radius:8px;' +
        'background:#f7f9fb;">' +

        '<div style="font-size:28px;font-weight:bold;color:#1683d8;">' +
        'Atlas Startpage' +
        '</div>' +

        '<div style="margin-top:8px;color:#63788a;">' +
        'Local operator dashboard' +
        '</div>' +

        '<div style="margin:22px 0 12px;">' +
        '<span style="font-weight:bold;">License:</span> ' +
        '<span class="' +
        (license.mode === 'ACTIVE' ? 'text-green' : 'text-orange') +
        '">Atlas ' +
        ChatStartpageClass.EscapeHtml(license.mode) +
        '</span>' +
        '&nbsp;&nbsp;&nbsp;' +
        '<span style="font-weight:bold;">Operator capacity:</span> ' +
        ChatStartpageClass.EscapeHtml(operatorCapacity) +
        '</div>' +

        '<div style="margin-top:18px;">' +
        moduleCard('PRO', 'Atlas PRO') +
        moduleCard('CSP', 'Startpage') +
        moduleCard('NGL', 'Geo Tracking') +
        moduleCard('NBL', 'Backlink Removal') +
        '</div>' +

        '</div>' +
        '</div>';

    return html;
};

ChatStartpageClass.prototype.createStartPagesArray = function (
    lz,
    ca,
    cr
) {
    if (!ChatStartpageClass.HasAtlasCspLicense()) {
        return [];
    }

    var startPages = [
        {
            name: 'Atlas Startpage',
            content: this.createSingleStartPage(),
            hash: 'atlas'
        }
    ];

    var customPages =
        Array.isArray(
            lzm_chatDisplay.startPages.others
        )
            ? lzm_chatDisplay.startPages.others
            : [];

    /*
     * Preserve supported customer pages, but accept only explicit
     * HTTP or HTTPS URLs.
     */
    for (
        var index = 0;
        index < customPages.length;
        index++
    ) {
        var customPage =
            customPages[index];

        if (
            !customPage ||
            typeof customPage.url !== 'string' ||
            !/^https?:\/\//i.test(customPage.url)
        ) {
            continue;
        }

        var customUrl =
            customPage.url;

        if (customPage.get_param != 0) {
            customUrl +=
                customUrl.indexOf('?') !== -1
                    ? '&'
                    : '?';

            customUrl +=
                'operator=' +
                encodeURIComponent(
                    String(DataEngine.myUserId || '')
                );
        }

        startPages.push({
            name:
                ChatStartpageClass.EscapeHtml(
                    customPage.title || 'Custom Page'
                ),

            content:
                '<div class="startpage-iframe-outer-div">' +
                '<iframe class="startpage-iframe" ' +
                'loading="lazy" ' +
                'referrerpolicy="no-referrer" ' +
                'src="' +
                ChatStartpageClass.EscapeHtml(customUrl) +
                '"></iframe>' +
                '</div>',

            hash:
                String(
                    customPage.hash || index
                )
        });
    }

    return startPages;
};

ChatStartpageClass.CreateOnboardingHTML = function () {
    if (!ChatStartpageClass.HasAtlasCspLicense()) {
        return '';
    }

    return '<div id="atlas-startpage-onboarding" ' +
        'style="padding:14px 24px;color:#63788a;">' +
        '<strong>Atlas setup checklist:</strong> ' +
        'configure operators and groups, create your chat button, ' +
        'configure invitations and email, and complete your knowledge base.' +
        '</div>';
};

ChatStartpageClass.ShowOnboarding = function () {
    if (
        !ChatStartpageClass.HasAtlasCspLicense() ||
        PermissionEngine.permissions.server_config != 1
    ) {
        $('#onboarding').html('');
        return false;
    }

    $('#onboarding').html(
        ChatStartpageClass.CreateOnboardingHTML()
    );

    return true;
};

ChatStartpageClass.SetOnboardingDone = function(_index,_ignore){

    var value = _ignore ? 2 : 1;
    LocalConfiguration.OnboardingDone = LocalConfiguration.OnboardingDone.substr(0, _index) + value + LocalConfiguration.OnboardingDone.substr(_index + 1);
    LocalConfiguration.Save();
    ChatStartpageClass.ShowOnboarding();
};

ChatStartpageClass.UpdateOnboardingDone = function(){

    if(!LocalConfiguration.OnboardingDone.length)
    {
        initLinkGenerator(null,false);
        for(var key in ChatStartpageClass.OnboardingElements)
        {
            var elem = ChatStartpageClass.OnboardingElements[key];
            var toAdd = '0';
            if(elem.id == 'onboarding-operators')
            {
                if(DataEngine.operators.idList.length > 1 || DataEngine.groups.idList.length > 1)
                    toAdd = '1';
            }
            if(elem.id == 'onboarding-chat-invites')
            {
                if(DataEngine.eventList.length)
                    toAdd = '1';
            }
            if(elem.id == 'onboarding-email')
            {
                if(DataEngine.global_configuration.database['email'].length)
                    toAdd = '1';
            }
            if(elem.id == 'onboarding-kb')
            {
                if(DataEngine.cannedResources.idList.length > 1)
                    toAdd = '1';
            }
            if(elem.id == 'onboarding-language')
            {
                if(ChatTranslationEditorClass.AvailableLanguages.server.length != 2 || ChatTranslationEditorClass.AvailableLanguages.mobile.length != 2)
                    toAdd = '1';
            }

            LocalConfiguration.OnboardingDone += toAdd;
        }
        LocalConfiguration.Save();
    }

    var dones = LocalConfiguration.OnboardingDone.split('');
    for(var key in dones)
    {
        var icon = $('#onboarding-icon-'+key.toString());

        if(dones[key] == '1')
        {
            icon.addClass('fa-check-circle');
            icon.removeClass('fa-circle-o');
            icon.addClass('icon-green');
            icon.removeClass('icon-gray');
        }
        else if(dones[key] == '2')
        {
            icon.addClass('fa-check-circle');
            icon.removeClass('fa-circle-o');
            icon.addClass('icon-green');
            icon.removeClass('icon-gray');
            $('#onboarding-'+key.toString()).css({display:'none'});
        }
        else
        {
            icon.removeClass('fa-check-circle');
            icon.addClass('fa-circle-o');
            icon.removeClass('icon-green');
            icon.addClass('icon-gray');
        }
    }
};
