//============================== FACEBOOK API INIT  ========================== //
if (((!Number.parseInt(wpdiscuzAjaxObj.fbUseOAuth2) && Number.parseInt(wpdiscuzAjaxObj.enableFbLogin)) || Number.parseInt(wpdiscuzAjaxObj.enableFbShare)) && wpdiscuzAjaxObj.facebookAppID) {
    (function (d, s, id) {
        let js, fjs = d.getElementsByTagName(s)[0];
        if (d.getElementById(id)) {
            return;
        }
        js = d.createElement(s);
        js.id = id;
        js.src = "//connect.facebook.net/en_US/sdk.js";
        fjs.parentNode.insertBefore(js, fjs);
    }(document, 'script', 'facebook-jssdk'));


    window.fbAsyncInit = function () {
        FB.init({
            appId: wpdiscuzAjaxObj.facebookAppID,
            cookie: true,
            xfbml: true,
            version: 'v7.0'
        });
    };
}

function wpcShareCommentFB(url, quote) {
    FB.ui({
        method: 'share',
        href: url,
        quote: quote,
    }, function (response) {
    });
}

//============================== GOOGLE API INIT  ========================== //

jQuery(document).ready(function ($) {
    wpdDisplayErrorMessage();
    if (Cookies.get('wpdiscuz_scroll_to_comments')) {
        Cookies.remove('wpdiscuz_scroll_to_comments', {path: '/'});
        $('html, body').animate({
            scrollTop: $('#comments').offset().top - 32
        }, 1000);
    }
    $('body').on('click', '.wpd-comment-share .fa-facebook-f', function () {
        if (wpdiscuzAjaxObj.enableFbShare != 1) {
            return;
        }
        let commentID = $(this).parents('.wpd-comment').find('.wpd-comment-right').attr('id');
        let postUrl = window.location.href;
        if (postUrl.indexOf('#') !== -1) {
            postUrl = postUrl.substring(0, postUrl.indexOf('#'));
        }
        postUrl += '#' + commentID;
        let commentContent = $(this).parents('.wpd-comment-right').find('.wpd-comment-text').text();
        wpcShareCommentFB(postUrl, commentContent);
    });

    let socialLoginProvider = '';
    $('body').on('click', '#wpdcom .wpd-social-login .wpdiscuz-login-button', function () {
        let socialLoginContainer = $(this).parents('.wpd-social-login');
        socialLoginProvider = wpdInitProvider($(this));
        wpdSocialLoginIsConfirmAgreement(socialLoginProvider, socialLoginContainer);
    });

    $('body').on('click', '#wpdcom .wpd-agreement-buttons-right .wpd-agreement-button', function () {
        let socialLoginContainer = $(this).parents('.wpd-form-wrap, .wpd-form').find('.wpd-social-login-agreement').slideUp(700);
        if ($(this).hasClass('wpd-agreement-button-agree')) {
            if (wpdiscuzAjaxObj.isCookiesEnabled) {
                Cookies.set('socialLoginAgreementConfirmed', 1, {expires: 30, path: '/'});
            }
            wpdCallSocialLogin(socialLoginProvider, socialLoginContainer);
        }
    });

    function wpdSocialLoginIsConfirmAgreement(provider, container) {
        if (Number.parseInt(wpdiscuzAjaxObj.socialLoginAgreementCheckbox) !== 1 || Cookies.get('socialLoginAgreementConfirmed') == 1) {
            wpdCallSocialLogin(provider, container);
        } else {
            container.parents('.wpd-form-wrap, .wpd-form').find('.wpd-social-login-agreement').first().slideDown(700);
        }
        return false;
    }


    function wpdCallSocialLogin(provider, container) {
        let token, userID = '';
        wpdSocialLoginLoadingBar(container, 1);
        Cookies.set('wpdiscuz_scroll_to_comments', 1, {path: '/'});
        if (provider === 'facebook' && wpdiscuzAjaxObj.facebookUseOAuth2 == 0) {
            FB.getLoginStatus(function (response) {
                if (response.status === 'connected') {
                    token = response.authResponse.accessToken;
                    userID = response.authResponse.userID;
                    wpdSendRequest(provider, token, userID, container);
                } else {
                    FB.login(function (response) {
                        if (response.status === 'connected') {
                            token = response.authResponse.accessToken;
                            userID = response.authResponse.userID;
                            wpdSendRequest(provider, token, userID, container);
                        }
                    }, {scope: 'public_profile,email'});
                }
            });
        } else {
            wpdSendRequest(provider, token, userID, container);
        }
    }

    function wpdSendRequest(provider, token, userID, container) {
        let data = new FormData();
        data.append('action', 'wpd_social_login');
        data.append('provider', provider);
        data.append('token', token || '');
        data.append('userID', userID || '');
        data.append('postID', wpdiscuzAjaxObj.wc_post_id);
        wpdiscuzAjaxObj.getAjaxObj(true, false, data).done(function (wpdiscuz_response) {
            wpdHandleResponse(wpdiscuz_response, container);
        });
    }

    function wpdHandleResponse(respons, container) {
        try {
            let obj = $.parseJSON(respons);
            let code = obj.code;
            let message = obj.message;
            let url = obj.url;
            if (Number.parseInt(code) === 200) {
                location.assign(url);
            } else {
                wpdiscuzAjaxObj.setCommentMessage(message, 'error');
            }
        } catch (e) {
            console.log(e);
        }
        wpdSocialLoginLoadingBar(container, 0);
    }

    function wpdDisplayErrorMessage() {
        let errorMessage = Cookies.get('wpdiscuz_social_login_message');
        if (errorMessage && errorMessage !== 'undefined') {
            Cookies.remove('wpdiscuz_social_login_message');
            wpdiscuzAjaxObj.setCommentMessage(decodeURIComponent(errorMessage.replace(/\+/g, '%20')), 'error');
        }
    }

    function wpdInitProvider($obj) {
        let provider = '';
        if ($obj.hasClass('wpdsn-fb')) {
            provider = 'facebook';
        }
        if ($obj.hasClass('wpdsn-insta')) {
            provider = 'instagram';
        }
        if ($obj.hasClass('wpdsn-gg')) {
            provider = 'google';
        }
        if ($obj.hasClass('wpdsn-ds')) {
            provider = 'disqus';
        }
        if ($obj.hasClass('wpdsn-wp')) {
            provider = 'wordpress';
        }
        if ($obj.hasClass('wpdsn-tw')) {
            provider = 'twitter';
        }
        if ($obj.hasClass('wpdsn-vk')) {
            provider = 'vk';
        }
        if ($obj.hasClass('wpdsn-linked')) {
            provider = 'linkedin';
        }
        if ($obj.hasClass('wpdsn-yandex')) {
            provider = 'yandex';
        }
        if ($obj.hasClass('wpdsn-weixin')) {
            provider = 'wechat';
        }
        if ($obj.hasClass('wpdsn-weibo')) {
            provider = 'weibo';
        }
        if ($obj.hasClass('wpdsn-qq')) {
            provider = 'qq';
        }
        if ($obj.hasClass('wpdsn-baidu')) {
            provider = 'baidu';
        }
        if ($obj.hasClass('wpdsn-telegram')) {
            provider = 'telegram';
        }
        return provider;
    }

    function wpdSocialLoginLoadingBar(container, show) {
        if (show === 1) {
            container.find('.wpdiscuz-social-login-spinner').show();
        } else {
            container.find('.wpdiscuz-social-login-spinner').hide();
        }
    }

//============================== TELEGRAM  ========================== //
    function haveTgAuthResult() {
        let locationHash = '', re = /[#\?\&]tgAuthResult=([A-Za-z0-9\-_=]*)$/, match;
        try {
            locationHash = location.hash.toString();
            if (match = locationHash.match(re)) {
                location.hash = locationHash.replace(re, '');
                let data = match[1] || '';
                data = data.replace(/-/g, '+').replace(/_/g, '/');
                let pad = data.length % 4;
                if (pad > 1) {
                    data += new Array(5 - pad).join('=');
                }
                return JSON.parse(window.atob(data));
            }
        } catch (e) {
            console.log(e);
        }
        return false;
    }

    let telegramUser = haveTgAuthResult();
    if (telegramUser) {
        $('#wpdiscuz-loading-bar').show();
        let tgData = new FormData();
        tgData.append('action', 'wpd_login_callback');
        tgData.append('provider', 'telegram');
        tgData.append('user', JSON.stringify(telegramUser));
        wpdiscuzAjaxObj.getAjaxObj(true, false, tgData).done(function (response) {
            if (response.success) {
                location.reload();
            } else {
                wpdiscuzAjaxObj.setCommentMessage(response.data, 'error');
                $('#wpdiscuz-loading-bar').fadeOut(250);
            }
        }).fail(function (jqXHR, textStatus, errorThrown) {
            console.log(errorThrown);
            $('#wpdiscuz-loading-bar').fadeOut(250);
        });
    }
});
