import { AccessToken, GraphRequest, GraphRequestManager, LoginManager } from 'react-native-fbsdk-next';
import { setToken } from '../api/api'
import { appSetToken, appSetUser, appSetFacebook } from '../redux/app/action'
import { login, disconnectFacebook } from '../api/UserApi'
import { store } from '../redux/store'
import { Alert } from 'react-native'
import NavigationService from '../utils/NavigationService';
import messaging from "@react-native-firebase/messaging";


let requestManager = new GraphRequestManager();

export function loginWithFacebook(onSuccess){
  LoginManager.logInWithPermissions(["public_profile","email"])
  .then(
    (result) => {
      if (!result.isCancelled || result.grantedPermissions.length !== permissions.length) {
        // console.log('login with facebook get access token')
        AccessToken.getCurrentAccessToken().then(
          (data) => {
            LoginManager.logOut()

            const accessToken = data.accessToken.toString()

            loginAccessTokenToServer(accessToken,onSuccess)
          }
        )
        // console.log("Login success with permissions: " + result.grantedPermissions.toString());
      }
    },
    function(error) {
      // console.log("Login fail with error: " + error);
    }
  );
}

async function loginAccessTokenToServer(accessToken,onSuccess){
  const fcm = messaging()
  if (!await fcm.hasPermission()) {
    try {
      await messaging().requestPermission()
    } catch (error) {
    }
  }

  const fcmToken = await messaging().getAPNSToken()

  let params = {
    access_token: accessToken,
    fcm_token: fcmToken
  }

  login(params)
    .then(async (res) => {
      if(res.status == 500){
        Alert.alert('','ไม่สามารถเชื่อมต่อกับเซิฟเวอร์ได้ กรุณาลองใหม่อีกครั้ง')
        return
      }

      if (res.ok) {
        if (res.data.token) {
          //Alert.alert('Connect with Facebook Success')
          setToken(res.data.token)
          store.dispatch(appSetToken(res.data.token))
          store.dispatch(appSetUser(res.data.user))
          onSuccess && onSuccess()
        }
      } else {
        if(res.data.msg != null){
          Alert.alert('',res.data.msg)
        }
      }
    })
}

export function logoutFacebook() {
  LoginManager.logOut()
}


export function disconnectWithFacebook(onSuccess){
        AccessToken.getCurrentAccessToken()
          .then((data) => {
            console.log("AccessToken.getCurrentAccessToken():")
            console.log(data)

            let accessToken = null;
            if(data && data.accessToken){
              accessToken = data.accessToken.toString();
            }
            //console.log("accessToken:")
            //console.log(accessToken)

            let params = {
                access_token: accessToken,
            }

              //alert(accessToken)
              //onSuccess && onSuccess()

              disconnectFacebook(params)
                .then(async (res) => {
                  if(res.status == 500){
                    Alert.alert('','ไม่สามารถเชื่อมต่อกับเซิฟเวอร์ได้ กรุณาลองใหม่อีกครั้ง')
                    return
                  }

                  if (res.ok) {
                      onSuccess && onSuccess();
                  } else {
                    if(res.data.msg != null){
                      Alert.alert('',res.data.msg)
                    }
                  }
                })



          }
        )


}
