All files / atlas-mobile-ts/src/components/Profile/ProfileSections ProfileInformation.tsx

0% Statements 0/81
0% Branches 0/47
0% Functions 0/26
0% Lines 0/80

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 
/* 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 { Formik } from "formik"
import React, { useEffect, useState } from "react"
import { ActivityIndicator, Alert, Button, StyleSheet, Text, TextInput, View, ViewStyle } from "react-native"
import Dialog from "react-native-dialog"
import { TouchableOpacity } from "react-native-gesture-handler"
import { colors, GlobalStyles } from "../../../utils/GlobalUtils"
import { PasswordForm, PasswordFormValues } from "../../PasswordForm"
import { ProfileSectionStyles } from "../Styles/ProfileSections.styles"
import { ProfileSection } from "./ProfileSection"
import * as Yup from 'yup';
import { PasswordFormStyles, PasswordValues } from "../../Auth/RegistrationSteps/RegisterPassword"
import { credsSchema, passwordSchema, profileCredsSchema, RegisterCredsValues } from "../../../utils/RegistrationUtils"
import { useProfile } from "../../../hooks/useProfile"
import { authStore } from "../../../libs/auth/AuthStore"
import { Landmark } from "../../../hooks/useLandmarks"
import { Separator } from "../../Separator"
 
interface ProfileInformationProps {
    openInfo: () => void
    infoCollapsed: boolean
    email: string
    username: string,
    changePassword: (password: string) => void
    changePasswordStatus: string
    resetChangePassword: () => void
    changeInfo: (info: RegisterCredsValues) => void
    changeInfoStatus: string
    resetChangeInfo: () => void
    deleteAccount: () => void
    deleteAccountStatus: string
}
 
export const ProfileInformation: React.FC<ProfileInformationProps> = (props) => {
    const [editingEnabled, toggleEditing] = useState<boolean>(false)
    const [deleteAccountDialogVisible, toggleDeleteAccountDialog] = useState<boolean>(false)
    const [formUsername, setUsername] = useState<string>(props.username)
    const [formEmail, setEmail] = useState<string>(props.email)
    const [password, setPassword] = useState<string>()
    const [changingPassword, toggleChangingPassword] = useState<boolean>(false)
    const [confirmPassword, setConfirmPassword] = useState<string>()
    const initialPasswordValues: PasswordValues = {password: password, confirmPassword: confirmPassword};
    const initialInfoValues: RegisterCredsValues = {username: formUsername, email: formEmail};
 
    useEffect(() => {
        Iif (props.changeInfoStatus == "error") {
            setEmail(props.email)
            setUsername(props.username)
        }
    }, [props.changeInfoStatus])
 
    useEffect(() => {
        Iif (props.infoCollapsed) {   
            toggleEditing(false)
        }
    }, [props.infoCollapsed])
 
    useEffect(() => {
        Iif (!editingEnabled) {
            toggleChangingPassword(false)
            setPassword('')
            setConfirmPassword('')
        }
    }, [editingEnabled])
 
    useEffect(() => {
        Iif (props.email) {
            setEmail(props.email)
        }
    }, [props.email])
 
    useEffect(() => {
        Iif (props.username) {
            setUsername(props.username)
        }
    }, [props.username])
 
    const InformationRow: React.FC<{fieldName: string, value: string, setText?: (value: string) => void, editable?: boolean, style?: ViewStyle}> = ({fieldName, value, editable, setText, style}) => {
        return (
            <View style={[style,GlobalStyles.itemRowContainer]}>
                <Text>{fieldName}:</Text>
                {editable ? <TextInput value={value} onChangeText={text => setText(text)}/> : <Text>{value}</Text> }
            </View>
        )
    }
 
    const submitInfo = async (formValues: RegisterCredsValues) => {   
        await props.changeInfo(formValues)
        setEmail(formValues.email)
        setUsername(formValues.username)
    }
 
    const cancelEditingInfo = () => {
        props.resetChangeInfo()
        setUsername(props.username)
        setEmail(props.email)
        toggleEditing(false)
    }
 
    const submitNewPassword = async (formValues: PasswordFormValues) => {
        await props.changePassword(formValues.password)
    }
 
    const cancelChangingPassword = () => {
        props.resetChangePassword()
        setPassword('')
        setConfirmPassword('')
        toggleEditing(false)
    }
 
    const tryDeleteAccount = async () => {
        await props.deleteAccount()
        toggleDeleteAccountDialog(false)
    }
 
    const StatusIndicator: React.FC<{status: string, cancelHandler: () => void, updateTarget: string}> = ({status, cancelHandler, updateTarget}) => {
        return (
            <View style={{justifyContent: "space-evenly", alignItems: "center", marginHorizontal: 20}}>
                <Text style={{color: 'black', fontSize: 20}}>{
                    status == 'loading' ? "Updating..." : 
                    status == 'error' ? "Something went wrong trying to change your " + updateTarget : null} 
                </Text>
                {
                    status == "loading" ? <ActivityIndicator style={{marginBottom: 10}} color='black' size="large"/> :
                    status == "error" ? <Button title="Okay" color="gray" onPress={cancelHandler}/> : null
                }
            </View>
        )
    }
 
    const ChangePasswordForm: React.FC = React.memo(() => {
        return (
            <Formik
            initialValues={initialPasswordValues}
            validationSchema={passwordSchema}
            enableReinitialize={true}
            onSubmit={values => submitNewPassword(values)}>
            {({ handleChange, handleBlur, handleSubmit, values, errors, touched }) => (
                <View style={{}}>
                    <TextInput 
                      style={{borderBottomWidth: 1, borderBottomColor: 'gray', marginBottom: 10, padding: 5}}
                      placeholder="New password" 
                      secureTextEntry={true} 
                      value={values.password}
                      onChangeText={handleChange('password')}
                      onBlur={handleBlur('password')} />
                    {errors.password && touched.password ? <Text style={PasswordFormStyles.errorText}>{errors.password}</Text> : null}
                    <TextInput 
                      style={{borderBottomWidth: 1, borderBottomColor: 'gray', marginBottom: 10, padding: 5}}
                      placeholder="Confirm password"
                      secureTextEntry={true} 
                      value={values.confirmPassword}
                      onChangeText={handleChange('confirmPassword')} 
                      onBlur={handleBlur('confirmPassword')} />
                    {errors.confirmPassword && touched.confirmPassword ? <Text style={PasswordFormStyles.errorText}>{errors.confirmPassword}</Text> : null}
                    <TouchableOpacity onPress={handleSubmit as any} style={styles.formButton}><Text style={{fontSize:17, color: 'dodgerblue'}}>Submit</Text></TouchableOpacity>
                    <TouchableOpacity onPress={cancelChangingPassword} style={styles.formButton}><Text style={{fontSize:17, color: colors.red}}>Cancel</Text></TouchableOpacity>
                </View>
              )}
        </Formik>
        )
    })
 
    const EditInfoForm: React.FC = () => {
        return (
            <Formik
                    initialValues={initialInfoValues}
                    validationSchema={profileCredsSchema}
                    enableReinitialize={true}
                    onSubmit={values => submitInfo(values)}>
                {({ handleChange, handleBlur, handleSubmit, values, errors, touched }) => (
                    <View style={{}}>
                        <TextInput 
                          style={{borderBottomWidth: 1, borderBottomColor: 'gray', marginBottom: 10, padding: 5}}
                          placeholder="Email" 
                          value={values.email}
                          onChangeText={handleChange('email')}
                          onBlur={handleBlur('username')} />
                        {errors.email && touched.email ? <Text style={PasswordFormStyles.errorText}>{errors.email}</Text> : null}
                        <TextInput 
                          style={{borderBottomWidth: 1, borderBottomColor: 'gray', marginBottom: 10, padding: 5}}
                          placeholder="Username"
                          value={values.username}
                          onChangeText={handleChange('username')} 
                          onBlur={handleBlur('username')} />
                        {errors.username && touched.username ? <Text style={PasswordFormStyles.errorText}>{errors.username}</Text> : null}
                        <TouchableOpacity onPress={handleSubmit as any} style={styles.formButton}><Text style={{fontSize:17, color: 'dodgerblue'}}>Save changes</Text></TouchableOpacity>
                        <TouchableOpacity onPress={() => toggleChangingPassword(true)} style={styles.formButton}><Text style={{fontSize:17, color: 'dodgerblue'}}>Change password</Text></TouchableOpacity>
                        <TouchableOpacity onPress={cancelEditingInfo} style={styles.formButton}><Text style={{fontSize:17, color: colors.red}}>Cancel</Text></TouchableOpacity>
                    </View>
                  )}
                </Formik>
        )
    }
 
    const DeleteAccountDialog: React.FC = () => {
        const [deleteAccountUsernameCheck, setDeleteAccountUsernameCheck] = useState<string>()
 
        return (
            <View>
                <Dialog.Container visible={deleteAccountDialogVisible}>
                    <Dialog.Title>Are you sure you want to delete your account?</Dialog.Title>
                    <Dialog.Description>{"All your data will be deleted, except for landmarks and comments that you have posted.\n\nYour subscription will be canceled, and any saved payment information will be purged.\n\n**THIS ACTION CANNOT BE UNDONE**"}</Dialog.Description>
                    <Dialog.Input label="Enter your username to continue (case sensitive)" onChangeText={text => setDeleteAccountUsernameCheck(text.trim())}/>
                    <Dialog.Button disabled={deleteAccountUsernameCheck !== props.username} style={deleteAccountUsernameCheck !== props.username ? {color: 'lightgray'} : {}} label="Delete my account" onPress={tryDeleteAccount}/>
                    <Dialog.Button label="Cancel" onPress={() => toggleDeleteAccountDialog(false)}/>
                </Dialog.Container>
            </View>
        )
    }
 
    return (
        <ProfileSection isCollapsed={props.infoCollapsed} collapseToggleMethod={props.openInfo} title="Information">
            {props.changePasswordStatus == "loading" || props.changePasswordStatus == "error" ? 
            <StatusIndicator status={props.changePasswordStatus} updateTarget="password" cancelHandler={cancelChangingPassword} /> :
            props.changeInfoStatus == "loading" || props.changeInfoStatus == "error" ? 
            <StatusIndicator status={props.changeInfoStatus} updateTarget="info" cancelHandler={cancelEditingInfo} /> :
            <>
                <DeleteAccountDialog />
                {changingPassword ? 
                <ChangePasswordForm /> : 
                <>
                    {editingEnabled && !changingPassword ? 
                    <EditInfoForm /> :
                    <>
                        <InformationRow style={{marginBottom: 10}} fieldName="Email" value={props.email}/>
                        <InformationRow style={{marginBottom: 20}} fieldName="Username" value={props.username} />
                        <TouchableOpacity onPress={() => toggleEditing(true)} style={styles.formButton}><Text style={{fontSize:17, color: 'dodgerblue'}}>Edit information</Text></TouchableOpacity>
                        <Separator style={{marginTop: 10}} color="lightgray" />
                        <TouchableOpacity onPress={() => toggleDeleteAccountDialog(true)} style={styles.formButton}><Text style={{fontSize:17, color: 'red'}}>Delete account</Text></TouchableOpacity>
                    </>}
                </>}
            </>}
        </ProfileSection>
    )
}
 
const styles = StyleSheet.create({
    formButton: {
        alignItems: 'center',
        padding: 5,
        borderRadius: 20,
        marginTop: 10
    },
 
    formInput: {
        borderBottomWidth: 1, 
        borderBottomColor: 'gray', 
        marginBottom: 10, padding: 5
    }
})