Untitled

 avatar
unknown
plain_text
2 years ago
34 kB
4
Indexable
// Customizable Area Start
//@ts-nocheck
//@ts-ignore
import { IBlock } from '../../../framework/src/IBlock';
import { Message } from '../../../framework/src/Message';
import { BlockComponent } from '../../../framework/src/BlockComponent';
import MessageEnum, {
  getName,
} from '../../../framework/src/Messages/MessageEnum';
import { runEngine } from '../../../framework/src/RunEngine';
import StorageProvider from '../../../framework/src/StorageProvider';
// Customizable Area Start
import { imgPasswordInVisible, imgPasswordVisible } from './assets';
import {
  auth as SpotifyAuth,
  remote as SpotifyRemote,
  ApiScope,
} from 'react-native-spotify-remote';
import messaging from '@react-native-firebase/messaging'
import NotifService from './NotifService'
import appleAuth, {
  appleAuthAndroid,
} from '@invertase/react-native-apple-authentication';

import { validationAnim } from '../../../components/src/Helper';
import { CommonContext } from '../../../components/src/CommonContextProvider';
import { BackHandler, Keyboard, Linking, NativeModules, Platform, ToastAndroid } from 'react-native'
import { stringify } from 'querystring'
import { Alert } from 'react-native'
import storage from 'framework/src/StorageProvider.web'
import { platform } from 'os'
import OneSignal from 'react-native-onesignal'
export const configJSON = require('./config')

export interface Props {
  navigation: any
  id: string
  // Customizable Area Start

  // Customizable Area End
}

interface S {
  // Customizable Area Start
  DeviceToken: any,
  AndroidDeiceToken: any,
  password: string
  email: string
  loading: boolean
  isInvalidEmail: boolean
  isInvalidPass: boolean
  isToggle: boolean
  isPasswordCheck: boolean
  isError: boolean
  errorMsg: string
  enablePasswordField: boolean
  checkedRememberMe: boolean
  indeterminate: boolean
  placeHolderEmail: string
  placeHolderPassword: string
  imgPasswordVisible: any
  imgPasswordInVisible: any
  progress: any
  labelHeader: string
  btnTxtLogin: string
  labelRememberMe: string
  btnTxtSocialLogin: string
  labelOr: string
  emailError: any
  passwordError: any
  showPassword: boolean
  rememberMe: boolean
  userCreds: any
  spotifyEmail: any
  spotifyExternalUrl: any
  spotifyUserId: any
  spotifyUserType: any
  spotifyAccessToken: any
  spotifyRefreshToken: any
  loader: boolean
  playerid: any
  Appletoken: any

  // Customizable Area End
}

interface SS {
  // Customizable Area Start
  id: any
  // Customizable Area End
}


let neha = {}


export default class EmailAccountLoginController extends BlockComponent<
  Props,
  S,
  SS
> {
  notificationPostApiCallId: any
  applemusicsignupApiCallId: any
  loginAccountApiCallId: any
  spotifyLoginApiCallId: any
  _unsubscribe: any
  animation: any
  spotifyConfig: any
  getjwtToken: any
  notif: any
  validationApiCallId: string = "";
  static contextType = CommonContext;
  constructor(props: Props,) {

    super(props)


    runEngine.attachBuildingBlock(this as IBlock, [
      getName(MessageEnum.RestAPIResponceMessage),
    ])
    this.receive = this.receive.bind(this)

    this.state = {
      Appletoken: '',
      DeviceToken: '',
      AndroidDeiceToken: '',
      playerid: '',
      email: '',
      password: '',
      progress: 0,
      loading: false,
      isInvalidEmail: false,
      isInvalidPass: false,
      isToggle: false,
      isPasswordCheck: false,
      isError: false,
      errorMsg: '',
      enablePasswordField: true,
      checkedRememberMe: false,
      indeterminate: false,
      placeHolderEmail: configJSON.placeHolderEmail,
      placeHolderPassword: configJSON.placeHolderPassword,
      imgPasswordVisible: configJSON.imgPasswordVisible,
      imgPasswordInVisible: imgPasswordInVisible,
      labelHeader: configJSON.labelHeader,
      btnTxtLogin: configJSON.btnTxtLogin,
      labelRememberMe: configJSON.labelRememberMe,
      btnTxtSocialLogin: configJSON.btnTxtSocialLogin,
      labelOr: configJSON.labelOr,
      userCreds: '',
      emailError: false,
      passwordError: false,
      showPassword: true,
      rememberMe: false,
      spotifyEmail: '',
      spotifyExternalUrl: '',
      spotifyUserId: '',
      spotifyUserType: '',
      spotifyAccessToken: '',
      spotifyRefreshToken: '',
      loader: false,
    }

    this.spotifyConfig = {
      // clientID: "3470398eb99c475389fd4f93148674f2",  cleint id of carl
      // clientID: 'd6844c47aecb4d26a67a27827937126d',
      // {....sagar client id}
      clientID: '3470398eb99c475389fd4f93148674f2',
      redirectURL: 'com.VibeSocialMusic://EmailAccountLoginBlock',
      //playURI: "spotify:artist:1fbo6ce8Pg6ZPWlpE3OkfQ",
      // tokenRefreshURL: "http://localhost:3000/spotify_refresh",
      // tokenSwapURL: "http://localhost:3000/spotify_swap",
      scopes: [
        ApiScope.PlaylistReadPrivateScope,
        ApiScope.PlaylistReadCollaborativeScope,
        ApiScope.PlaylistModifyPublicScope,
        ApiScope.PlaylistModifyPrivateScope,
        ApiScope.UserFollowReadScope,
        ApiScope.UserFollowModifyScope,
        ApiScope.UserLibraryReadScope,
        ApiScope.UserLibraryModifyScope,
        // ApiScope.UserReadBirthDateScope,
        ApiScope.UserReadEmailScope,
        ApiScope.UserReadPrivateScope,
        ApiScope.UserTopReadScope,
        ApiScope.UGCImageUploadScope,
        ApiScope.StreamingScope,
        ApiScope.AppRemoteControlScope,
        ApiScope.UserReadPlaybackStateScope,
        ApiScope.UserReadPlaybackPosition,
        ApiScope.UserModifyPlaybackStateScope,
      ],
    }
  }

  // animate = () => {
  //   let progress = 0
  //   this.setState({ progress })
  //   setTimeout(() => {
  //     this.setState({ indeterminate: false })
  //     setInterval(() => {
  //       progress += Math.random() / 5
  //       if (progress > 1) // istanbul ignore next
  //       {
  //         progress = 1
  //       }
  //       this.setState({ progress })
  //     }, 500)
  //   }, 10)
  // }

  setUserToken = async (userData: any) => {
    //  console.log('user detials on email login page>>', userData)

    const _userDetails = JSON.stringify(userData.data.attributes)
    this.notificationcallapi(userData.meta.token)
    await StorageProvider.set('USER_TOKEN', userData.meta.token)
    await StorageProvider.set('USER_DETAILS', _userDetails)
    await StorageProvider.set('USER_ID', userData.data.id)
    console.log( "zxxxxxxxcdddddd", userData.meta.token)
    const ud = await StorageProvider.get('USER_ID')
    await StorageProvider.set('REMEMBER_CHECK', 'success')
    // istanbul ignore next
    if (this.state.isToggle === true) 
    {
      // console.log('token when remember me on >>>', this.state.isToggle)
    }
  }



  // did
  async componentDidMount(): Promise<void> {
    //this.jwtTokenCreation()

    // this.createPlayerID()
    this.RememberMe()
  }



  async receive(from: string, message: Message) {
    
    if (
      getName(MessageEnum.RestAPIResponceMessage) === message.id &&
      this.applemusicsignupApiCallId !== null &&
      this.applemusicsignupApiCallId ===
      message.getData(getName(MessageEnum.RestAPIResponceDataMessage))
    ) // istanbul ignore next
    {
      this.applemusicsignupApiCallId = null

      var responseJson = message.getData(
        getName(MessageEnum.RestAPIResponceSuccessMessage),
      )

      
      if (responseJson && !responseJson.errors) // istanbul ignore next
      {
        this.notificationcallapi(responseJson.meta.token)
        await StorageProvider.set('PLATFORM', 'apple')
        // this.context.platformData('apple')
        await StorageProvider.set('USER_TOKEN',responseJson.meta.token)
        console.log( "zxxxxxxxcdddddd",responseJson.meta.token)
        this.setState({ loader: false })
        if (responseJson.data?.attributes?.genre_selected) // istanbul ignore next
        {
          this.props.navigation.navigate('FeedBlock')
        } else // istanbul ignore next
        {
          this.props.navigation.navigate('Customform')
        }

      } else if (responseJson.errors) // istanbul ignore next
      {
        console.log('Post Api Error')
        console.log(responseJson, 'Post Api Error')

        // this.setState({ loader: false })
      } else // istanbul ignore next
      {
        console.log(responseJson, "error")
        // this.setState({ loader: false })
        // this.parseApiErrorResponse(responseJson.data)
      }
    }

    if (
      getName(MessageEnum.RestAPIResponceMessage) === message.id &&
      this.notificationPostApiCallId !== null &&
      this.notificationPostApiCallId ===
      message.getData(getName(MessageEnum.RestAPIResponceDataMessage))
    ) // istanbul ignore next
    {
      this.notificationPostApiCallId = null

      var responseJson = message.getData(
        getName(MessageEnum.RestAPIResponceSuccessMessage),
      )

      
      if (responseJson && !responseJson.errors) // istanbul ignore next
      {
        console.log(responseJson, "responseofthenoti")
      } else if (responseJson.errors) // istanbul ignore next
      {
        // this.setState({ loader: false })
      } else // istanbul ignore next
      {
        console.log(responseJson, "error")
        // this.parseApiErrorResponse(responseJson.data)
      }
    }

    if (
      getName(MessageEnum.RestAPIResponceMessage) === message.id &&
      this.getjwtToken !== null &&
      this.getjwtToken ===
      message.getData(getName(MessageEnum.RestAPIResponceDataMessage))
    ) // istanbul ignore next
    {
      var responseJson = message.getData(
        getName(MessageEnum.RestAPIResponceSuccessMessage),
      )
      console.log('connect account api response>>>', responseJson.data)
      await StorageProvider.set('APPLE_JWT_TOKEN', responseJson.data)
    }

    if (
      getName(MessageEnum.RestAPIResponceMessage) === message.id &&
      this.loginAccountApiCallId !== null &&
      this.loginAccountApiCallId ===
      message.getData(getName(MessageEnum.RestAPIResponceDataMessage))
    ) // istanbul ignore next
    {
      this.setState({ loader: false })
      var responseJson = message.getData(
        getName(MessageEnum.RestAPIResponceSuccessMessage),
      )

      if (
        responseJson &&
        !responseJson.errors &&
        responseJson.data &&
        responseJson.meta.token
      ) // istanbul ignore next
      {
        this.setState({ loader: false })
        await StorageProvider.set('PLATFORM', 'spotify')
        // this.context.platformData('spotify')
        await StorageProvider.set('IDOFTHECURRENTUSER', responseJson.data.id)
        await StorageProvider.set('TASTEMAKER_ID', JSON.stringify(responseJson.data.attributes.tastemaker_id))
        this.loginAccountSuccessCallBack(responseJson)
      } else 
      {
        //Check Error Response
        this.loginAccountFailureCallBack(responseJson)
        // this.parseApiErrorResponse(responseJson);
      }
      // this.parseApiCatchErrorResponse(errorResponse);
    } else if 
    (
      getName(MessageEnum.RestAPIResponceMessage) === message.id &&
      this.spotifyLoginApiCallId !== null &&
      this.spotifyLoginApiCallId ===
      message.getData(getName(MessageEnum.RestAPIResponceDataMessage))
    ) // istanbul ignore next
    {
      this.spotifyLoginApiCallId = null
      this.setState({ loader: false })

      var responseJson = message.getData(
        getName(MessageEnum.RestAPIResponceSuccessMessage),
      )
      var errorResponse = message.getData(
        getName(MessageEnum.RestAPIResponceErrorMessage),
      )
      console.log('using spotify api', responseJson)

      if (
        responseJson &&
        !responseJson.errors &&
        !responseJson.data.errors &&
        responseJson.meta.token
      ) // istanbul ignore next
      {
        await StorageProvider.set('IDOFTHECURRENTUSER',responseJson.data.id)
        await StorageProvider.set('TASTEMAKER_ID',JSON.stringify(responseJson.data.attributes.tastemaker_id))
        await StorageProvider.set('PLATFORM','spotify')
        // this.context.platformData('spotify')
        this.spotifyLoginSuccessCallBack(responseJson)
      } else if (responseJson.errors) // istanbul ignore next
      {
        this.spotifyLoginFailureCallBack(responseJson)
        this.parseApiErrorResponse(responseJson)
      } else // istanbul ignore next
      {
        this.spotifyLoginFailureCallBack(responseJson)
        this.parseApiErrorResponse(responseJson.data)
      }

    }
  }

  RememberMe=async()=>{
   let email = await StorageProvider.get('LOGIN_USERNAME')
   let password = await StorageProvider.get('LOGIN_PASSWORD')
   console.log("ffrwroifnojnejrnvef",this.context.rememberme)  // istanbul ignore next
 if(this.context.rememberme === true){  
    this.setState({email : email})
    this.setState({password: password})
    this.setState({isToggle : true})
 }else if(this.context.rememberme === false){ 
    this.setState({email : ''})
    this.setState({password: ''})
    this.setState({isToggle : false}) 
 }
  }
  notificationcallapi = async (userData: any) => {
    const _token = await StorageProvider?.get('USER_TOKEN')

    const _devicetoken = await StorageProvider?.get('Player_ID')

    this.setState({ loader: true })
    const header = {
      'Content-Type': 'multipart/form-data',
      token: userData,
    }
    var formdata = new FormData()

    formdata.append('account[device]', Platform.OS)
    formdata.append('account[device_token]', _devicetoken)

    const requestMessage = new Message(
      getName(MessageEnum.RestAPIRequestMessage),
    )

    this.notificationPostApiCallId = requestMessage.messageId

    requestMessage.addData(
      getName(MessageEnum.RestAPIResponceEndPointMessage),
      'https://vibesocialmusic-82830-ruby.b82830.dev.us-east-1.aws.svc.builder.cafe/create_device_token',
    )

    requestMessage.addData(
      getName(MessageEnum.RestAPIRequestHeaderMessage),
      JSON.stringify(header),
    )
    requestMessage.addData(
      getName(MessageEnum.RestAPIRequestBodyMessage),
      formdata,
    )
    requestMessage.addData(
      getName(MessageEnum.RestAPIRequestMethodMessage),
      configJSON.loginAPiPostMethod,
    )

    runEngine.sendMessage(requestMessage.id, requestMessage)
    return true

  }
  spotifyLoginSuccessCallBack = async (responseJson: any) => {
    // console.log('@@@ spotify Success Response============', responseJson)
    await this.setUserToken(responseJson)
    Keyboard.dismiss()
    this.setState({ loading: false })
    // istanbul ignore next
    if (
      !responseJson?.data?.attributes?.account_connected &&
      !responseJson?.data?.attributes?.genre_selected
    )
    {
      // console.log(
      //   'from login using spotify goning  to streaming if account not activated and genre not selected>>',
      // )
      this.props.navigation.navigate('Streaming', {
        genre: responseJson?.data?.attributes?.genre_selected,
      })
    } else if (
      responseJson?.data?.attributes?.account_connected &&
      !responseJson?.data?.attributes?.genre_selected
    ) // istanbul ignore next
    {
      // console.log(
      //   'from login using spotify goning to customform if account connected>>',
      // )
      this.props.navigation.navigate('Customform')
    } else if (
      !responseJson?.data?.attributes?.account_connected &&
      responseJson?.data?.attributes?.genre_selected
    ) // istanbul ignore next
    {
      // console.log(
      //   'from login using spotify goning to streaming if genre selected>>',
      // )
      this.props.navigation.navigate('Streaming', {
        genre: responseJson?.data?.attributes?.genre_selected,
      })
    } else // istanbul ignore next
    {
      // console.log('from login using spotify goning to FeedBlock>>>')
      this.props.navigation.navigate('FeedBlock')
    }
  }

  spotifyLoginFailureCallBack = (errorResponse: any) => {
    this.setState({ loading: false })
    // console.log('@@@ spotify Error Response =========', errorResponse)
  }

  spotifyLoginApi = async () => {
    this.setState({ loader: true })
    var formdata = new FormData()

    formdata.append('type', 'social_account')
    formdata.append('account[email]', this.state.spotifyEmail)
    formdata.append(
      'account[spotify_external_urls]',
      `{ spotify:${this.state.spotifyExternalUrl}}`,
    )
    formdata.append('account[user_name]', this.state.spotifyEmail.split('@')[0])
    formdata.append('account[spotify_user_id]', this.state.spotifyUserId)
    formdata.append('account[spotify_user_type]', this.state.spotifyUserType)
    formdata.append(
      'account[spotify_access_token]',
      this.state.spotifyAccessToken,
    )
    formdata.append(
      'account[spotify_refresh_token]',
      this.state.spotifyAccessToken,
    )

    // console.log('full data in spotify login api >>>>', formdata)
    const header = {
      'Content-Type': 'multipart/form-data',
    }

    const requestMessage = new Message(
      getName(MessageEnum.RestAPIRequestMessage),
    )

    this.spotifyLoginApiCallId = requestMessage.messageId

    requestMessage.addData(
      getName(MessageEnum.RestAPIResponceEndPointMessage),
      configJSON.createApiEndPoint,
    )

    requestMessage.addData(
      getName(MessageEnum.RestAPIRequestHeaderMessage),
      JSON.stringify(header),
    )

    requestMessage.addData(
      getName(MessageEnum.RestAPIRequestBodyMessage),
      formdata,
    )

    requestMessage.addData(
      getName(MessageEnum.RestAPIRequestMethodMessage),
      configJSON.loginAPiPostMethod,
    )

    // console.log(
    //   '@@@ Request ===========',
    //   requestMessage,
    //   this.spotifyLoginApiCallId,
    // )
    runEngine.sendMessage(requestMessage.id, requestMessage)
    return true
  }

  loginAccountSuccessCallBack = async (responseJson: any) => {
    this.setState(
      {
        loading: false,
        isInvalidPass: false,
        isInvalidEmail: false,
      },
     // () => alert('Login Successfully'),
    )
    await this.setUserToken(responseJson)
    // this.onSpotifyLogin()
    // console.log('@@@ Login Success Response============', responseJson)
    Keyboard.dismiss()
    this.setState({ loading: false })
    // istanbul ignore next
    if (
      !responseJson?.data?.attributes?.account_connected &&
      !responseJson?.data?.attributes?.genre_selected
    ) 
    {
      // console.log(
      //   'from login goning  using email and pass to streaming if account not activated and genre not selected>>',
      // )
      this.props.navigation.navigate('Streaming', {
        genre: responseJson?.data?.attributes?.genre_selected,
      })
    } else if (
      responseJson?.data?.attributes?.account_connected &&
      !responseJson?.data?.attributes?.genre_selected
    ) // istanbul ignore next
    {
      // console.log('from login  using email and pass goning to customform if account connected>>')
      this.props.navigation.navigate('Customform')
    } else if (
      !responseJson?.data?.attributes?.account_connected &&
      responseJson?.data?.attributes?.genre_selected
    ) // istanbul ignore next
    {
      // console.log('from login  using email and pass goning to streaming if genre selected>>')
      this.props.navigation.navigate('Streaming', {
        genre: responseJson?.data?.attributes?.genre_selected,
      })
    } else // istanbul ignore next
    {
      // console.log('from login using email and pass goning to FeedBlock>>>')
      this.props.navigation.navigate('FeedBlock')
    }
  }

  loginAccountFailureCallBack = (errorResponse: any) => {
    this.setState({
      loader: false,
      email: '',
      password: '',
      isInvalidPass: true,
      isInvalidEmail: true,
      isError: true,
      progress: 0,
    })
    // console.log('@@@ Login Error Response =========', errorResponse)
    this.setState({ errorMsg: errorResponse.errors[0].failed_login })
    // this.showAlert('Failed_login:', "Login Failed");
  }

  validationCheck = async () => {
    // console.log('check validation')
    //let reg = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/
    //let reg = /^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/
    let reg = /^[a-z]+[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/
    let regPass = /^(?=.*?[A-Z])(?=(.*[a-z]){1,})(?=(.*[\d]){1,})(?=(.*[\W]){1,})(?!.*\s).{4,}$/
    
    if (!reg.test(this.state.email)) // istanbul ignore next
    {
      this.setState({ isInvalidEmail: true })
    } else // istanbul ignore next
    {
      this.setState({ isInvalidEmail: false })
    }


    if (regPass.test(this.state.password)) // istanbul ignore next
    {
      this.setState({ isInvalidPass: false })
    } else // istanbul ignore next
    {
      this.setState({ isInvalidPass: true })
    }

    setTimeout(() => {
      let validationLength = validationAnim([
        !this.state.isInvalidEmail,
        !this.state.isInvalidPass,
      ])  // istanbul ignore next
      // console.log('validationLength', validationLength)  

      switch (validationLength) {
        case 0:
          this.setState({ progress: 0 })
          break

        case 1:
          this.setState({ progress: 0.5 })
          break

        case 2:
          this.setState({ progress: 1 })
          break
      }
    }, 400)
  }


  doEmailLogin = async () => {
    this.setState({ loader: true })
    const header = {
      'Content-Type': configJSON.loginApiContentType,
    }

    const attrs = {
      email: this.state.email,
      password: this.state.password,
    }

    const data = {
      type: 'email_account',
      attributes: attrs,
    }

    //console.log('request of email login >>>>', data)
    const httpBody = {
      data: data,
    }

    const requestMessage = new Message(
      getName(MessageEnum.RestAPIRequestMessage),
    )

    this.loginAccountApiCallId = requestMessage.messageId

    requestMessage.addData(
      getName(MessageEnum.RestAPIResponceEndPointMessage),
      configJSON.loginAPiEndPoint,
    )

    requestMessage.addData(
      getName(MessageEnum.RestAPIRequestHeaderMessage),
      JSON.stringify(header),
    )

    requestMessage.addData(
      getName(MessageEnum.RestAPIRequestBodyMessage),
      JSON.stringify(httpBody),
    )

    requestMessage.addData(
      getName(MessageEnum.RestAPIRequestMethodMessage),
      configJSON.loginAPiPostMethod,
    )

    runEngine.sendMessage(requestMessage.id, requestMessage)
    return true
  }



  handleForgotPassword = () => {
    Keyboard.dismiss()
    this.props.navigation.navigate('ForgotPasswordOTP')
  }

  

  handlePasswordCheck = () => {
    this.setState({ isPasswordCheck: !this.state.isPasswordCheck,})                                      
  }


  onSpotifyLogin = async () => {
    try {
      // await SpotifyAuth.endSession()
      this.setState({ loader: true })
      const session = await SpotifyAuth.authorize(this.spotifyConfig)
      await SpotifyRemote.connect(session.accessToken);

      // await SpotifyRemote.seek(58000);

      console.log('getting spotify data>>>>>', session)
      let refresh = await StorageProvider.set("REFRESH_TOKEN", session.refreshToken)
      // console.log(refresh)
      // istanbul ignore next
      if (!session) 
      {
        this.setState({ loader: false })
      }
      this.setState({
        spotifyAccessToken: session.accessToken,
        spotifyRefreshToken: session.refreshToken,
      })
      this.getUserData(session)
    } catch (error) {

      this.setState({ loader: false })
      // console.log('user cancle login>>', error)
    }
  }

  getUserData = async (accessToken: any) => {
    // console.log('spotify token>>>>', accessToken.accessToken)
    //  let refresh =  await StorageProvider.set("REFRES", accessToken.refreshToken)


    try {
      let response = await fetch(`https://api.spotify.com/v1/me`, {
        headers: {
          Authorization: 'Bearer ' + accessToken.accessToken,
        },
      })
      this.setState({ loader: false })
      let json = await response.json()
      // console.log('spotify user login api response >>>>>', json)
      await StorageProvider.set('USER_TOKEN_SPOTIFY', accessToken.accessToken)

      this.setState(
        {
          spotifyEmail: json.email,
          spotifyUserId: json.id,
          spotifyUserType: json.type,
          spotifyExternalUrl: json.external_urls.spotify,
        },
        () => this.spotifyLoginApi(),
      )
    } catch (error) {
      // console.log('@@@ User Data Success fail for spotiry ============', error)
      Alert.alert(
        'Alert',
        'Your Spotify Email is not linked with Spotify Console.',
        [
          {
            text: 'OK',
            onPress: () => null,
          },
        ],
      )
      this.setState({ loader: false })
    }
  }

  moveToNextScreen = (screenName: string) => {
    //BackHandler.removeEventListener("hardwareBackPress", this.handleBackButton),
    Keyboard.dismiss()
    this.props.navigation.navigate(screenName)
  }

  checkNativeIOS = async () => {
    try {
      var jwt = await StorageProvider.get('APPLE_JWT_TOKEN')  //developer token 
      var result = await NativeModules.AppleMusicAuthentication.authAppleMusic(jwt);
      await StorageProvider.set('APPLE_MUSIC_TOKEN', result)
      console.log('Succeed to get Apple Music user token. User token >> ', result);

    } catch (e:any) {
      console.log('Failed to get Apple Music user token. Error >> ', e.code, e.massage)
    }
  }

  checkNativeAndroid = async () =>{

    try {
      const userToken = await NativeModules.AppleMusicAuthenticationModule.authAppleMusic("eyJ0eXAiOiJKV1QiLCJhbGciOiJFUzI1NiIsImtpZCI6IlQzVERXOTg1UEYifQ.eyJpc3MiOiIyNkEyQlVVQ1E5IiwiaWF0IjoxNjcyMDUzNTU0LjI3NzQ3MywiZXhwIjoxNjgwNjkzNTU0LjI3NzQ3M30.KcZPYGxWkf0bEEG4JVG1ZyafXqDdwyur9qy9QP5Ayx4qwIjT8dDvb9jWbVBYayTJzYVXJdsF3xNY2scdwcvRVg")
      // console.log("Getting a new UserToken", { userToken });
    } catch (e) {
      console.log("Getting a new UserToken", { e });
    }
  }

  jwtTokenCreation = async () => {

    const header = {
      'Content-Type': 'application/json',
    }

    const requestMessage = new Message(
      getName(MessageEnum.RestAPIRequestMessage),

    )
    this.getjwtToken = requestMessage.messageId
    requestMessage.addData(
      getName(MessageEnum.RestAPIResponceEndPointMessage),
      'https://vibesocialmusic-82830-ruby.b82830.dev.us-east-1.aws.svc.builder.cafe/apple_jwt'
    )
    requestMessage.addData(
      getName(MessageEnum.RestAPIRequestHeaderMessage),
      JSON.stringify(header)
    )

    requestMessage.addData(
      getName(MessageEnum.RestAPIRequestMethodMessage),
      'POST',
    )

    runEngine.sendMessage(requestMessage.id, requestMessage)

    return true
  }

  onPressLoginWithApple1 = async () => {
    console.log("button");
    try {
      const appleAuthRequestResponse = await appleAuth.performRequest({
        requestedOperation: appleAuth.Operation.LOGIN,
        requestedScopes: [appleAuth.Scope.EMAIL, appleAuth.Scope.FULL_NAME],
      });

      // get current authentication state for user
      // /!\ This method must be tested on a real device. On the iOS simulator it always throws an error.
      const credentialState = await appleAuth.getCredentialStateForUser(appleAuthRequestResponse.user);
      console.log("Main Token Apple Token ", appleAuthRequestResponse);

      this.setState(
        {
          Appletoken: appleAuthRequestResponse.identityToken
        },
        () => this.appleMusicAPI(),

      )
      // use credentialState response to ensure the user is authenticated
      // istanbul ignore next
      if (credentialState === appleAuth.State.AUTHORIZED) 
      {
        this.jwtTokenCreation()
        this.checkNativeIOS()
      }

      Keyboard.dismiss()
    } catch (error) {
      Alert.alert(
        'Alert',
        'Your Apple Music is not connected.',
        [
          {
            text: 'OK',
            onPress: () => null,
          },
        ],
      )
      this.setState({ loader: false })
      // console.log('user cancle login>>', error)
    }
  }

  onPressLoginWithAndroid = async () => {
    try {
      appleAuthAndroid.configure({
        clientId: 'com.engineer.vibesocialmusic',
        redirectUri: 'https://vibesocialmusic-82830-ruby.b82830.dev.us-east-1.aws.svc.builder.cafe/callback',
        scope: appleAuthAndroid.Scope.ALL,
        responseType: appleAuthAndroid.ResponseType.ALL,
      })
      const response = await appleAuthAndroid.signIn()
      // istanbul ignore next
      if (response) 
      {
        const code = response.code // Present if selected ResponseType.ALL / ResponseType.CODE
        const id_token = response.id_token // Present if selected ResponseType.ALL / ResponseType.ID_TOKEN

        const user = response.user // Present when user first logs in using appleId
        const state = response.state // A copy of the state value that was passed to the initial request.
        console.log("@@@ Responce", response);
        console.log('@@@ Got auth code', code)
        console.log('@@@ Got id_token', id_token)
        console.log('@@@ Got user', user)
        console.log('@@@ Got state', state)
        this.setState(
          {
            Appletoken: id_token
          },
          () => this.appleMusicAPI(),
        )
        // if () {
        //   this.jwtTokenCreation()
        //  this.checkNativeIOS()
        // }
        Keyboard.dismiss()
      }

    } catch (error:any) {
      if (error && error.message) // istanbul ignore next
      {
        console.log(error)
        switch (error.message) {
          case appleAuthAndroid.Error.NOT_CONFIGURED:
            // console.log('appleAuthAndroid not configured yet.')
            break
          case appleAuthAndroid.Error.SIGNIN_FAILED:
            // console.log('Apple signin failed.')
            break
          case appleAuthAndroid.Error.SIGNIN_CANCELLED:
            // console.log('User cancelled Apple signin.')
            break
          default:
            break
        }
      }
    }
  }



  appleMusicAPI = async () => {
    let formData = new FormData()
    formData.append('account[apple_token]', this.state.Appletoken)
    const header = {
      'Content-Type': 'multipart/form-data',
    }
    const requestMessage = new Message(
      getName(MessageEnum.RestAPIRequestMessage),
    )
    this.applemusicsignupApiCallId = requestMessage.messageId
    requestMessage.addData(
      getName(MessageEnum.RestAPIResponceEndPointMessage),
      "https://vibesocialmusic-82830-ruby.b82830.dev.us-east-1.aws.svc.builder.cafe/apple_account_create",
    )

    requestMessage.addData(
      getName(MessageEnum.RestAPIRequestHeaderMessage),
      JSON.stringify(header),
    )

    requestMessage.addData(
      getName(MessageEnum.RestAPIRequestBodyMessage),
      formData,
    )

    requestMessage.addData(
      getName(MessageEnum.RestAPIRequestMethodMessage),
      'POST',
    )
    // console.log(
    //   '@@@ Request ===========',
    //   requestMessage,
    //   this.spotifyLoginApiCallId,
    // )
    runEngine.sendMessage(requestMessage.id, requestMessage)
    return true
  }


  finalAppleMusicLogin = async () => {
    //1) apple login (will pass identy token then we will get vibe token)
    //2) jwt creation 
    //3) Apple music user token 
    this.onPressLoginWithApple1()
    //this.checkNativeIOS() 
  }

  handleRememberMe = async (e) => {
    this.setState({ isToggle: !this.state.isToggle })
    if(e === false){
      this.setState({email: ''})
      this.setState({password: ''})
      this.context.rememberMe(e)
     }

    await StorageProvider.set('LOGIN_USERNAME', this.state.email)
    await StorageProvider.set('LOGIN_PASSWORD', this.state.password)
    this.context.rememberMe(e)
    console.log("Remember Me---->",this.context.rememberme)
  
  }


  // handleRememberMe = () => {
  //   this.setState({ rememberMe: !this.state.rememberMe })
  // }

    // handleShowPassword = () => {
  //   this.setState({ showPassword: !this.state.showPassword })
  // }

  // handlePassword = (text: any) => {
  //   // console.log(' Value in Password>>', text)
  //   // let reg = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6,}$/
  //   let reg = /^(?=.*?[A-Z])(?=(.*[a-z]){1,})(?=(.*[\d]){1,})(?=(.*[\W]){1,})(?!.*\s).{6,}$/
  //   if (reg.test(text) === false) // istanbul ignore next
  //   {
  //     // console.log('password is Not Correct')
  //     this.setState({ password: text, passwordError: true })
  //     return false
  //   } else // istanbul ignore next
  //   {
  //     this.setState({ password: text, passwordError: false })
  //     // console.log('password is Correct')
  //   }
  // }


    // handleEmail = (text: any) => {
  //   // console.log('value in email>>', text)
  //   let reg = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w\w+)+$/
  //   if (reg.test(text) === false) {
  //     // console.log('Email is Not Correct')

  //     this.setState({ email: text, emailError: true })
  //     return false
  //   } else {
  //     this.setState({ email: text, emailError: false })
  //     // console.log('Email is Correct')
  //   }
  // }


  // handleSignUp = () => {
  //   Keyboard.dismiss()
  //   this.props.navigation.navigate('DynamicContent')
  // }
 

  // handleLogin = () => {
  //   if (
  //     this.state.email === null ||
  //     this.state.email.length === 0 ||
  //     this.state.emailError
  //   ) // istanbul ignore next
  //   {
  //     alert('Please Enter Email')
  //     return false
  //   }

  //   if (
  //     this.state.password === null ||
  //     this.state.password.length === 0 ||
  //     this.state.passwordError
  //   ) // istanbul ignore next
  //   {
  //     alert('Please Enter Password')
  //     return false
  //   }
  //   alert('Api Integration is Under Progress')
  // }

}
// Customizable Area End
// Customizable Area End
Editor is loading...