# Code coverage report for atlas-mobile-ts/src/components/Profile/Profile.tsx

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

0% Statements 0/60
0% Branches 0/14
0% Functions 0/13
0% Lines 0/60

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

     ﻿/* 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 { ImageInfo } from 'expo-image-picker/build/ImagePicker.types';
    import * as WebBrowser from 'expo-web-browser';
    import { observer } from "mobx-react";
    import React, { useEffect, useState } from "react";
    import { ActivityIndicator, Alert, AppState, Button, Image, ImageBackground, ScrollView, Text, TouchableOpacity, View } from 'react-native';
    import { renderers } from 'react-native-popup-menu';
    import { useAuth } from "../../hooks/useAuth";
    import { useProfile } from "../../hooks/useProfile";
    import { authStore } from "../../libs/auth/AuthStore";
    import { API_URL, reportAxiosError } from '../../utils/RequestUtils';
    import { PhotoPicker } from '../PhotoPicker';
    import { ProfileHeader } from "./ProfileHeader";
    import { ProfileSections } from "./ProfileSections";
    import { ProfileMainStyles } from "./Styles/Profile.styles";
    const {SlideInMenu} = renderers

    /**
     * The screen component that displays the user's profile. Gets user information from the {@link useProfile} hook.
     * @component
     */
    const Profile: React.FC = () => {
        const [changingPassword, toggleChangingPassword] = useState<boolean>(false)
        const [photoSourceMenuOpened, togglePhotoSourceMenu] = useState<boolean>(false)
        const [newPhotoB64, setNewPhoto] = useState<string>()
        const [loadingImg, setLoadingImg] = useState<boolean>(false)
        const [uploadingImg, setUploadingImg] = useState<boolean>(false)
        const {
            profile,
            changePasswordAsync,
            changePasswordStatus,
            resetChangePassword,
            updateProfile,
            updateProfileStatus,
            resetUpdateProfile,
            toggleTipsAsync,
            refetchProfile,
            deleteAccount,
            deleteAccountStatus
        } = useProfile(authStore.userId)

        useEffect(() => {
            Iif (newPhotoB64) {
                Alert.alert("Confirm new picture", "Are you sure you want to change your profile picture?",
                    [
                        {text: 'Yes', onPress: async () => await uploadPhoto()},
                        {text: 'No', onPress: cancelNewPhoto}
                    ])
                }
        }, [newPhotoB64])

        const initiateNewPhotoSelect = async () => {
            togglePhotoSourceMenu(false)
            setLoadingImg(true)
        }

        const onPhotoSelected = async (result: ImageInfo) => {
            setNewPhoto(result.base64)
            setLoadingImg(false)
        }

        const uploadPhoto = async () => {
            setUploadingImg(true)
            let photoData = new FormData()
            photoData.append('profPic', 'data:image/png;base64,' + newPhotoB64);

            try {
                const response = await axios({
                  method: 'post',
                  url: API_URL + '/api/user-profile/change-picture/' + authStore.userId + '/',
                  headers: { "Authorization": "Bearer " + authStore.accessToken, },
                  timeout: 50000,
                  data: photoData,
                });

                Iif (response.status == 200) {
                    await refetchProfile()
                    Alert.alert("You successfully changed your profile picture!")
                    setUploadingImg(false)
                }

            } catch (error) {
                reportAxiosError("[ProfileData]: Something went wrong when changing a profile picture", error, true)
                Alert.alert("Something went wrong when changing your profile picture.")
            }
        }

        const cancelNewPhoto = () => {
            togglePhotoSourceMenu(false)
            setLoadingImg(false)
            setNewPhoto('')
        }

        const PrivacyLink: React.FC = () => {
            /**
             * Opens up the company privacy policy in the browser.
             */
            const openPrivacyPolicy = async () => {
                await WebBrowser.openBrowserAsync(API_URL + "/privacy")
            }

            return (
                <TouchableOpacity onPress={openPrivacyPolicy}>
                    <Text style={ProfileMainStyles.privacyButtonText}>Privacy policy</Text>
                </TouchableOpacity>
            )
        }
        const LogoutButton: React.FC = () => {
            const {logout} = useAuth()

            return (
                <TouchableOpacity style={ProfileMainStyles.logoutButtonContainer} onPress={async () => await logout()}>
                    <Text style={ProfileMainStyles.logoutButtonText}>Logout</Text>
                </TouchableOpacity>
            )
        }

        return (
            <ImageBackground source={require('../../../assets/cover.jpg')} style={ProfileMainStyles.profileMainContainer}>
                <ScrollView contentContainerStyle={{justifyContent: "flex-end", alignItems: 'center', padding: 10}}>
                    {loadingImg || uploadingImg ?
                    <View style={{marginVertical: 30}}>
                        <Text style={{color: 'white', fontSize: 20, marginBottom: 10}}>{
                            loadingImg ? 'Loading image...' :
                            uploadingImg ? 'Uploading image' : null }
                        </Text>
                        <ActivityIndicator color='white' size="large"/>
                    </View> :
                    <ImageBackground style={ProfileMainStyles.profileImage} source={newPhotoB64 ? {uri: 'data:image/png;base64,' + newPhotoB64} : profile?.image_b64 ? {uri: 'data:image/png;base64,' + profile?.image_b64} : require('../../../assets/default-pfp.png')}>
                        <TouchableOpacity style={{width: "100%", height: "100%", zIndex: 12}} onPress={() => togglePhotoSourceMenu(true)} >
                            <View style={ProfileMainStyles.profileImageOverlay}>
                                <Text style={{fontSize: 12, textAlign: 'center', color: 'white', opacity: 1}}>Change profile picture</Text>
                            </View>
                        </TouchableOpacity>
                    </ImageBackground> }

                    <View style={ProfileMainStyles.profileSubContainer}>
                        <Text style={ProfileMainStyles.headerUsername}>{profile?.username}</Text>
                        <ProfileHeader profile={profile} />
                        <ProfileSections
                            resetChangeInfo={resetUpdateProfile}
                            changeInfo={updateProfile}
                            changeInfoStatus={updateProfileStatus}
                            resetChangePassword={resetChangePassword}
                            changePasswordStatus={changePasswordStatus}
                            deleteAccount={deleteAccount}
                            deleteAccountStatus={deleteAccountStatus}
                            profile={profile}
                            toggleTipsAsync={toggleTipsAsync}
                            changePassword={changePasswordAsync} />
                        <LogoutButton />
                        <PrivacyLink />
                    </View>
                </ScrollView>
                <PhotoPicker multiple={false} menuType='alert' cancel={cancelNewPhoto} photoSourceMenuOpened={photoSourceMenuOpened} onBeforeLaunchPicker={initiateNewPhotoSelect} onReceivedPhotoResult={result => onPhotoSelected(result)} />
            </ImageBackground>
        )
    }

    export default observer(Profile)