// This is called with the results from from FB.getLoginStatus().
function statusChangeCallback(response) {
  // console.log('statusChangeCallback');
  // console.log(response);
  if (response.status === 'connected') {
    //chamaAPI();
  } else if (response.status === 'not_authorized') {
    // The person is logged into Facebook, but not your app.
    document.getElementById('status').innerHTML = 'Please log ' + 'into this app.';
  } else {
    // The person is not logged into Facebook, so we're not sure if
    // they are logged into this app or not.
    document.getElementById('status').innerHTML = 'Please log ' + 'into Facebook.';
  }
}
function checkLoginState() {
  FB.getLoginStatus(function(response) {
    statusChangeCallback(response);
  });
}

function carregarFacebookAPI() {
  FB.init({
    appId: $('#btnAppFacebook').data('facebook-id'),
    cookie: true, // enable cookies to allow the server to access
    // the session
    xfbml: true, // parse social plugins on this page
    version: 'v12.0',
  });

  // FB.getLoginStatus(function(response) {
  //   statusChangeCallback(response);
  // });
}

// Load the SDK asynchronously

(function(d, s, id) {
  var js,
    fjs = d.getElementsByTagName(s)[0];
  if (d.getElementById(id)) return;
  js = d.createElement(s);
  js.id = id;
  js.src = 'https://connect.facebook.net/pt_BR/sdk.js';
  fjs.parentNode.insertBefore(js, fjs);
})(document, 'script', 'facebook-jssdk');

// Here we run a very simple test of the Graph API after login is
// successful.  See statusChangeCallback() for when this call is made.
function chamaAPI(accessToken) {
  var tipoValidacaoSocial = $('#btnAppFacebook').data('tipo-validacao-social');

  // console.log('Welcome!  Fetching your information.... ');
  FB.api('/me', { fields: 'name,first_name,last_name, email' }, function(response) {
    // console.log('Successful login for: ' + response.name);
    $.ajax({
      url: 'index.php?route=account/login/socialLogin',
      type: 'post',
      data: {
        emailRedeSocial: response.email,
        nomeRedeSocial: response.name,
        primeiroNomeRedeSocial: response.first_name,
        sobrenomeRedeSocial: response.last_name,
        idRedeSocial: response.id,
        origemLogin: 'facebook',
        tokenloginsocial: accessToken,
        tipo_validacao_social: tipoValidacaoSocial,
      },
      dataType: 'json',
      success: function(json) {
        if (!(tipoValidacaoSocial == 'vincular')) {
          if (json['login']) {
            if (window.location.href.indexOf('route=checkout/checkout') != -1) {
              location.reload();
            } else {
              document.formlogin.submit();
            }
          } else {
            notificationMsg(json['warning'], 'warning');
            $("input[name='email']").val(json['emailRedeSocial']);
            $("input[name='firstname']").val(json['primeiroNomeRedeSocial']);
            $("input[name='lastname']").val(json['sobrenomeRedeSocial']);
          }
        } else {
          if (!json['warning_login_vinculado']) {
            const btn_vinculo_facebook = document.getElementById('btnAppFacebook');
            const txt_vinculo_facebook = document.getElementById('text-vinculo-facebook');
            if (json['login_vinculado']) {
              txt_vinculo_facebook.textContent = 'Desconectar';
              btn_vinculo_facebook.onclick = function(event){
                event.preventDefault();
                event.stopPropagation();
                facebookUnlink();
              };
              notificationMsg($('#btnAppFacebook').data('text-facebook-vinculado'), 'success');
            } else {
              txt_vinculo_facebook.textContent = 'Conectar';
              btn_vinculo_facebook.onclick = function(event){
                event.preventDefault();
                event.stopPropagation();
                loginFacebook();
              };
              notificationMsg($('#btnAppFacebook').data('text-facebook-desvinculado'), 'success');
            }
          } else {
            notificationMsg(json['warning_login_vinculado'], 'warning');
          }
        }
      },
    });
  });

}

window.loginFacebook = function(fcClkOrigem) {
  try {
    carregarFacebookAPI();
    FB.login(
      function(response) {
        // console.log('statusChangeCallback');
        // console.log(response);
        if (response.status === 'connected') {
          chamaAPI(response.authResponse.accessToken);
        }
      },
      {
        scope: 'public_profile,email', // escopos de permissão para acesso.
        enable_profile_selector: true,
      }
    );
  } catch (e) {
    alert('Verifique se você tem acesso liberado ao Facebook(https://www.facebook.com/).');
  }
};

window.facebookUnlink = function(fcClkOrigem){
  try {
    carregarFacebookAPI();
    // talvez aqui vai chamar o FB.logout

    $.ajax({
      url: 'index.php?route=account/account/unlink_social_media_access',
      type: 'post',
      dataType: 'json',
      data: {
        ajax: true,
        redesocial: 'facebook',
      },
    }).done(function(json) {
      if(json['result']){
        const btn_vinculo_facebook = document.getElementById('btnAppFacebook');
        const txt_vinculo_facebook = document.getElementById('text-vinculo-facebook');
        txt_vinculo_facebook.textContent = 'Conectar';
        btn_vinculo_facebook.onclick = function(event){
          event.preventDefault();
          event.stopPropagation();
          loginFacebook();
        };
        notificationMsg($('#btnAppFacebook').data('text-facebook-desvinculado'), 'success');
      } else {
        notificationMsg('Ocorreu um erro ao fazer o desvinculo dos dados do Facebook!', 'warning');
      }
    }).fail(function(json) {
        console.log('error');
        console.log(json);
    });


  } catch (e) {
    alert('Verifique se você tem acesso liberado ao Facebook(https://www.facebook.com/).');
  }
};
