/* Copyright (C) Click & Push Accessibility, Inc - All Rights Reserved
 * Unauthorized copying of this file, via any medium is strictly prohibited
 * Proprietary and confidential
 * Written and maintained by the Click & Push Development team 
 * <dev@clicknpush.ca>, January 2022
 */

import axios from 'axios';
import React, { useState } from 'react';
import { Image, TouchableOpacity, View } from 'react-native';
import 'react-native-get-random-values';
import { ActivityIndicator, Text } from 'react-native-paper';
import { RegisterStepProps, stepMessages } from '../RegisterMain';
import {useAuth} from '../../../../data/Auth/AuthContext'
import {Separator} from '../../../Separator'
import {PrimaryButton, SecondaryButton} from '../../../Buttons'
import {PhotoPicker} from '../../../PhotoPicker'

/**
 * This component displays an interface to upload a profile picture
 */
const RegisterImage: React.FC<RegisterStepProps> = ({changeStep, formValues}) => {
  const {sendApiRequestAsync} = useAuth()

  /**
   * Stores the base64 of the user's selected profile pic
   */ 
  const [photoBase64, setPhotoBase64] = useState<string>();
  /**
   * This flag is set to true when the registration submission is being processed. An activity spinner will display while it is true
   */ 
  const [loadingSubmission, toggleLoading] = useState<boolean>(false);
  /**
   * This flag toggles the menu that is used to choose a photo source (Library or Camera).
   */ 
  const [photoSourceMenuOpened, togglePhotoSourceMenu] = useState<boolean>(false)

  /**
     * Reverse back to measurements step
     */ 
  const back = () => {
    console.log("[Registration]: Registration form values updated")
    changeStep(2, stepMessages[2])
  }

  /**
   * Prepares and sends a registration request to the api
   */ 
  const register = async () => {
    // toggle the loading flag and change status
    toggleLoading(true);
    changeStep(4, 'Hang tight for a moment while we create your account.')

    // create FormData and send request
    const formData = prepareFormData()    
    await sendRegisterRequest(formData)
  }

  // Returns a FormData object containing all the form values from each registration step, including the image (in b64) chosen on this step
  const prepareFormData = (): FormData =>  {
    console.log("[Registration]: Preparing form data...")
    let formData = new FormData();
    let processedFormValues;
    if (formValues.height && formValues.weight) {
      processedFormValues = {...formValues, height: parseFloat(formValues.height), weight: parseFloat(formValues.weight)}
    }
    else {
      processedFormValues = {
        email: formValues.email,
        username: formValues.username,
        password: formValues.password,
      };
    }
    formData.append('userInfo', JSON.stringify(processedFormValues));
    formData.append('avatar', 'data:image/png;base64,' + photoBase64);

    console.log("[Registration]: Form data prepared")
    return formData
  }

  const sendRegisterRequest = async (formData: FormData) => {
    // initialize registration result message
    let resultMessage = '';

    console.log("[Registration]: Sending registration request...")
    // send request, notify user of result

    try {
      const response = await sendApiRequestAsync({
        axiosConfig: {
          method: 'post',
          url: '/api/register/',
          timeout: 50000,
          data: formData,
        },
        authorized: false,
        errorMessage: 'There was an error registering your account. Please try again.',
        loggingCategory: 'PROFILE'
      });
      if (response.status == 200) {
        resultMessage = 'Success! Congratulations on registering for your new account, you can now login!';  
      }
      
    } catch (error) {}

    toggleLoading(false);
    changeStep(5, resultMessage); 
  }

  return (
    <View>
      { !loadingSubmission ?
      <View>
        <TouchableOpacity onPress={() => togglePhotoSourceMenu(true)} style={{justifyContent: 'center', }}>
          { photoBase64 != null ?
          <Image style={{alignSelf: 'center', borderRadius: 100, width: 200, height: 200, marginBottom: 5, marginTop: 30,}} source={{uri: 'data:image/png;base64,' + photoBase64}} /> :
          <Image style={{alignSelf: 'center', borderRadius: 100, width: 200, height: 200, marginBottom: 5, marginTop: 30,}} source={require('../../../../../assets/default-pfp.png')} /> 
          }   
          <Text style={{alignSelf: 'center', marginVertical: 20, color: 'white'}}>Choose photo</Text>
        </TouchableOpacity>
        <View style={{margin: 20}}>
          <Separator color="lightgray" />
          <PrimaryButton text="Register" onPress={register} style={{marginVertical: 20}} />
          <SecondaryButton text="Previous" onPress={back} style={{marginBottom: 20}} />
        </View> 
      </View>
      : 
      <View>
          <ActivityIndicator style={{marginTop: 200}} size="large" animating={true} color="red"/>
      </View>}
      <PhotoPicker menuType='alert' multiple={false} photoSourceMenuOpened={photoSourceMenuOpened} cancel={() => togglePhotoSourceMenu(false)} onReceivedPhotoResult={result => setPhotoBase64(result.base64)}/>
    </View>
    
  )
}
 
export default RegisterImage;
 