(function ($) {
    /**
     * Check Pages
     */
    function flexyconsent_checkPages() {
        var rootOfPage = 'flexyconsent_page_flexyconsent-';
        var requiredRules = [
            {
                'apiKey': [
                    'userSettingsPage',
                    'updateUserSettingsPage',
                    'updateEmailPage',
                    'deleteAccountPage',
                    'dashboardPage',
                    'projectSettingsPage',
                    'subscriptionPage',
                    'cookieManagerPage'
                ],
                "projectId": [
                    'dashboardPage',
                    'updateEmailPage',
                    'projectSettingsPage',
                    'subscriptionPage',
                    'paymentPage',
                    'cookieManagerPage'
                ],
                "removedPages": [
                    'deleteAccountPage',
                    'updateEmailPage',
                    'updateUserSettingsPage',
                    'paymentPage',
                ]
            }
        ]

        // Define options and pages will show together
        requiredRules.forEach(element => {
            $.each(element, function (key, value) {
                if (flexyconsentData[key]) {
                    value.forEach(element => {
                        $('a[href="' + 'admin.php?page=flexyconsent-' + element + '"]').css({ 'display': 'block' });
                    })
                } else {
                    value.forEach(element => {
                        if (rootOfPage + element === flexyconsentData.currentScreen.id) {
                            if (!requiredRules[0].removedPages.includes(element)) { // Don't redirect if it is removedPages
                                // flexyconsentGoMainPageGlobal('startPage');
                                flexyconsentGoPage('startPage');
                            }
                        }
                        $('a[href="' + 'admin.php?page=flexyconsent-' + element + '"]').hide();
                    })
                }
            })
        })
        // Define options and pages won't show together
        // var noRequiredRules = [
        //     {
        //         'projectId': [
        //             'projectSelectCreatePage',
        //         ]
        //     }
        // ]
        // noRequiredRules.forEach(element => {
        //     $.each(element, function (key, value) {
        //         if (flexyconsentData[key]) {
        //             value.forEach(element => {
        //                 $('a[href="' + 'admin.php?page=flexyconsent-' + element + '"]').hide();
        //                 $('a[href="' + 'admin.php?page=' + element + '"]').hide();
        //                 $('a[href="' + flexyconsentData.redirectRoot + element + '"]').hide();
        //                 // $('a[href="' + flexyconsentData.redirectMainRoot + element + '"]').hide();
        //             })
        //         }
        //     })
        // })
        if (flexyconsentData['apiKey'] && flexyconsentData['projectId']) {
            $('a[href="' + 'admin.php?page=' + 'flexyconsent-dashboardPage' + '"]').hide();
            $('a[href="' + 'admin.php?page=' + flexyconsentData.redirectRoot + 'flexyconsent-dashboardPage' + '"]').hide();
            $('ul.wp-submenu li a[href="' + 'admin.php?page=' + 'flexyconsent-startPage' + '"]').attr('href', 'admin.php?page=flexyconsent-dashboardPage').text(flexyconsentData.dashboard);
        }
    }
    /**
     * Add Contact Link
     */
    function flexyconsent_add_contact_link() {
        $('li.toplevel_page_flexyconsent-startPage ul').append('<li class="contact"><a href="https://flexyconsent.com/#contact" style="display: block;" target="_blank">' + flexyconsentData.contactUs + '</a></li>');
    }
    /**
     * Call Functions
     */
    $(document).ready(function () {
        flexyconsent_checkPages();
        flexyconsent_add_contact_link();
        getScriptCode();
    });
    /**
     * Helpers
     */
    function flexyconsentGoMainPageGlobal(page) {
        location.href = flexyconsentData.redirectMainRoot + page
    }

    function flexyconsentGoPage(page) {
        location.href = flexyconsentData.redirectRoot + page
    }

    function getScriptCode() {
        if (flexyconsentData.projectScriptSrc && flexyconsentData.updateTime && new Date().getTime() - flexyconsentData.updateTime < 1000 * 60 * 60 * 24)
            return;
        if (!flexyconsentData.email)
            return;

        $.ajax({
            url: flexyconsentData.endpoint + 'scriptcode',
            type: 'POST',
            data: JSON.stringify(
                {
                    email: flexyconsentData.email,
                    apiKey: flexyconsentData.apiKey,
                    projectId: flexyconsentData.projectId,
                    projectTypeId: 2
                }
            ),
            contentType: "application/json; charset=utf-8",
            success: function (response) {
                if (response.statusCode === 0) {
                    if (response.pageCodeScriptUrl) {
                        if (flexyconsentData.projectScriptSrc !== response.pageCodeScriptUrl) {
                            console.log('Page code url: not equal');
                            const options = [{ key: 'scriptSrc', value: response.pageCodeScriptUrl }, { key: 'updateTime', value: new Date().getTime() }];
                            if (flexyconsentData.projectScript) {
                                options.push({ key: 'script', value: "" });
                            }
                            saveOptions(options);
                        } else {
                            console.log('Page code url: equal');
                            const options = [{ key: 'updateTime', value: new Date().getTime() }];
                            saveOptions(options);
                        }
                    } else {
                        console.log('No page code url!!');
                    }

                } else {
                    console.log('Error: ' + response.statusMessage);
                }
            },
            error: function (error) {
                console.log(error);
            }
        });

        function saveOptions(options) {
            $.ajax({
                url: flexyconsentData.resturl + 'flexyconsent/v1/option',
                type: 'POST',
                beforeSend: function (xhr) {
                    xhr.setRequestHeader('X-WP-Nonce', flexyconsentData.nonce);
                },
                data: jQuery.param({ updates: options }),
                contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
                success: function (response) {
                    console.log('Options saved');
                },
                error: function (error) {
                    console.log(error);
                }
            });
        }
    }
}(jQuery));