import { AccessToken, GraphRequest, GraphRequestManager, LoginManager } from 'react-native-fbsdk';
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';


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);
    }
  );
}

function loginAccessTokenToServer(accessToken,onSuccess){
  let params = {
    access_token: accessToken,
  }
  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)

            const 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) {
                      Alert.alert('Disconnect with Facebook Success')
//                    if (res.data.token) {
//                      setToken(res.data.token)
//                      store.dispatch(appSetToken(res.data.token))

                      this.state.user.fb_token = null
                      this.state.user.fb_is_link = 'f'
                        //Alert.alert(this.state.user)
                        //console.log('console.log(this.state.user):')
                        //console.log(this.state.user)
//                      store.dispatch(appSetUser(this.state.user))
//                      store.dispatch(appSetFacebook('f'))
                      onSuccess && onSuccess()
//                    }
                  } else {
                    if(res.data.msg != null){
                      Alert.alert('',res.data.msg)
                    }
                  }
                })



          }
        )


}
