import appleAuth, {
  AppleAuthRequestOperation,
  AppleAuthRequestScope,
  AppleAuthCredentialState,
} from '@invertase/react-native-apple-authentication';

import { setToken } from '../api/api'
import { store } from '../redux/store'
import {appSetToken, appSetUser} from '../redux/app/action';
import {login, register} from '../api/UserApi';
import {Alert} from 'react-native';

export const signinApple = async (onSuccess) => {
  try {
    const requestOptions = {
      requestedOperation: AppleAuthRequestOperation.LOGIN,
      requestedScopes: [AppleAuthRequestScope.EMAIL, AppleAuthRequestScope.FULL_NAME],
    }

    // register({
    //   ...this.props.user,
    //   device_id: deviceId
    // }).then((res) => {
    //
    // });

    // login
    /* const { user } = await appleAuth.performRequest(requestOptions);
    console.log(user) */

    // register
    const appleAuthRequestResponse = await appleAuth.performRequest({
      requestedOperation: AppleAuthRequestOperation.LOGIN,
      requestedScopes: [AppleAuthRequestScope.EMAIL, AppleAuthRequestScope.FULL_NAME],
    })


    console.log(appleAuthRequestResponse)

    // get current authentication state for user
    // /!\ This method must be tested on a real device. On the iOS simulator it always throws an error
    // use credentialState response to ensure the user is authenticated
    if (AppleAuthCredentialState.AUTHORIZED) {
      // user is authenticated
      // sent and login
      let params = {
        identityToken: appleAuthRequestResponse.identityToken,
        authorizationCode: appleAuthRequestResponse.authorizationCode,
        email_apple: appleAuthRequestResponse.email
      }

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

    }
  } catch (e) {
    console.log(e);
    if (e.code === 'ERR_CANCELED') {
      // handle that the user canceled the sign-in flow
    } else {
      // handle other errors
    }
  }
}
