Wavelength/components/home/Relationships.tsx

318 lines
9.3 KiB
TypeScript
Raw Permalink Normal View History

2024-10-11 13:46:46 -05:00
import React, { useEffect, useState } from 'react';
import { Image, StyleSheet, AppState } from 'react-native';
2024-10-11 13:46:46 -05:00
import { ThemedView } from '@/components/ThemedView';
import { ThemedText } from '@/components/ThemedText';
import { getUserData } from '@/components/services/securestorage/UserData';
2024-10-14 13:48:22 -05:00
import {
saveRelationshipData,
getRelationshipData
} from '@/components/services/securestorage/RelationshipData';
2024-10-11 13:46:46 -05:00
import Button from '@/components/buttons/Button';
import { Colors } from '@/constants/Colors';
import { useColorScheme } from '@/hooks/useColorScheme';
import RequestRelationship from '@/components/home/RequestRelationship';
2024-10-14 13:48:22 -05:00
import type { User, Relationship, RelationshipData } from '@/components/Types';
2024-10-11 13:46:46 -05:00
type RelationshipProps = {
profilePictureUrl: string | null;
};
const Relationships: React.FC<RelationshipProps> = ({ profilePictureUrl }) => {
const scheme = useColorScheme() ?? 'light';
const [status, setStatus] = useState<RelationshipData | null>(null);
2024-10-14 13:48:22 -05:00
const [user, setUser] = useState<User | null>(null);
const [showRequestRelationship, setShowRequestRelationship] = useState(false);
2024-10-11 13:46:46 -05:00
const [loading, setLoading] = useState(true);
useEffect(() => {
fetchRelationshipStatus();
setupPeriodicCheck();
2024-10-11 13:46:46 -05:00
}, []);
useEffect(() => {
2024-10-14 13:48:22 -05:00
if (profilePictureUrl && user) {
setUser(prevUserData =>
prevUserData ? {...prevUserData, pfpURL: profilePictureUrl} : null);
2024-10-11 13:46:46 -05:00
}
}, [profilePictureUrl]);
2024-10-14 13:48:22 -05:00
const handleRequestSent = (data: RelationshipData) => {
setStatus(data);
setShowRequestRelationship(false);
}
const setupPeriodicCheck = () => {
let intervalId: NodeJS.Timeout | null = null;
const startChecking = () => {
checkRelationshipStatus();
2024-10-14 13:48:22 -05:00
intervalId = setInterval(checkRelationshipStatus, 60000);
};
const stopChecking = () => {
if (intervalId) {
clearInterval(intervalId);
intervalId = null;
}
};
const handleAppStateChange = (nextAppState: string) => {
2024-10-14 13:48:22 -05:00
if (nextAppState === 'active') startChecking();
else stopChecking();
};
const subscription = AppState.addEventListener('change', handleAppStateChange);
2024-10-14 13:48:22 -05:00
if (AppState.currentState === 'active') startChecking();
return () => {
stopChecking();
subscription.remove();
2024-10-14 13:48:22 -05:00
}
};
2024-10-11 13:46:46 -05:00
const fetchRelationshipStatus = async () => {
setLoading(true);
2024-10-11 13:46:46 -05:00
try {
2024-10-14 13:48:22 -05:00
const userFromStorage: User = await getUserData() as User;
if (!userFromStorage || !userFromStorage.id)
throw new Error("User or user data not found");
setUser(userFromStorage);
const storedRelationshipData = await getRelationshipData();
2024-10-14 13:48:22 -05:00
if (storedRelationshipData)
setStatus(storedRelationshipData);
await checkRelationshipStatus();
} catch (error) {
2024-10-14 13:48:22 -05:00
console.log('Error fetching relationship status:', error)
} finally {
setLoading(false);
}
};
const checkRelationshipStatus = async () => {
try {
2024-10-14 13:48:22 -05:00
const userFromStorage: User = await getUserData() as User;
if (!userFromStorage || !userFromStorage.id)
throw new Error("User or user data not found");
const response = await fetch(
`${process.env.EXPO_PUBLIC_API_URL}/relationships/getRelationshipData` +
`?userId=${userFromStorage.id}`, {
2024-10-11 13:46:46 -05:00
headers: {
'x-api-key': process.env.EXPO_PUBLIC_API_KEY ?? '',
},
});
if (!response.ok) {
const errorData = await response.json();
2024-10-14 13:48:22 -05:00
throw new Error(
errorData.message ||
`HTTP error! status: ${response.status}`
);
2024-10-11 13:46:46 -05:00
}
const data = await response.json() as RelationshipData;
2024-10-11 13:46:46 -05:00
setStatus(data);
await saveRelationshipData(data);
2024-10-11 13:46:46 -05:00
} catch (error) {
console.log('No relationship found or error checking status:', error);
setStatus(null);
2024-10-11 13:46:46 -05:00
} finally {
2024-10-14 13:48:22 -05:00
setLoading(false);
2024-10-11 13:46:46 -05:00
}
};
2024-10-14 13:48:22 -05:00
const handleUpdateRelationshipStatus =
async (newStatus: 'accepted' | 'rejected') => {
if (!status || !status.relationship) {
console.error('No relationship to update');
return;
}
try {
2024-10-14 13:48:22 -05:00
const response = await fetch(
`${process.env.EXPO_PUBLIC_API_URL}/relationships/updateStatus`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-api-key': process.env.EXPO_PUBLIC_API_KEY ?? '',
},
body: JSON.stringify({
relationshipId: status.relationship.id,
status: newStatus,
}),
});
if (!response.ok) {
const errorData = await response.json();
2024-10-14 13:48:22 -05:00
throw new Error(
errorData.message ||
`HTTP error! status: ${response.status}`
);
}
const result = await response.json();
2024-10-14 13:48:22 -05:00
if (result) await checkRelationshipStatus();
else throw new Error('Failed to update relationship status');
} catch (error) {
console.error('Error updating relationship status:', error);
}
};
const handleAcceptRequest = () => handleUpdateRelationshipStatus('accepted');
const handleRejectRequest = () => handleUpdateRelationshipStatus('rejected');
2024-10-11 13:46:46 -05:00
if (loading) {
return <ThemedText>Loading...</ThemedText>;
}
2024-10-14 13:48:22 -05:00
const renderRelationshipContent = () => {
if (!status || !status.relationship) {
// Case 1: Not in a relationship
return showRequestRelationship ? (
<RequestRelationship onRequestSent={handleRequestSent} />
) : (
2024-10-14 13:48:22 -05:00
<Button
width={220} height={60}
onPress={() => setShowRequestRelationship(true)}
>
<ThemedText
style={[
styles.buttonLabel,
{color: Colors[scheme].background}
]}
>
2024-10-11 13:46:46 -05:00
Request Relationship
</ThemedText>
</Button>
);
} else if (status.relationship.status === 'pending') {
// Case 2 & 3: Pending relationship (we can't differentiate who requested it)
return (
<>
2024-10-14 13:48:22 -05:00
<ThemedText style={styles.title}>
Pending Relationship
</ThemedText>
<ThemedView style={styles.profileContainer}>
<ThemedView style={styles.profileWrapper}>
<Image
2024-10-14 13:48:22 -05:00
source={{
uri: `${process.env.EXPO_PUBLIC_URL}` +
`${status.partner.pfpURL}`
}}
style={styles.profilePicture}
/>
2024-10-14 13:48:22 -05:00
<ThemedText style={styles.name}>
{status.partner.fullName}
</ThemedText>
</ThemedView>
</ThemedView>
<ThemedView style={styles.buttonContainer}>
<Button width={100} height={40} onPress={handleAcceptRequest}>
2024-10-14 13:48:22 -05:00
<ThemedText
style={[
styles.buttonLabel,
{color: Colors[scheme].background}
]}
>
Accept
</ThemedText>
</Button>
<Button width={100} height={40} onPress={handleRejectRequest}>
2024-10-14 13:48:22 -05:00
<ThemedText
style={[
styles.buttonLabel,
{color: Colors[scheme].background}
]}
>
Reject
</ThemedText>
</Button>
</ThemedView>
</>
);
} else if (status.relationship.status === 'accepted') {
// Case 4: In an accepted relationship
return (
<>
2024-10-14 13:48:22 -05:00
<ThemedText style={styles.title}>
{status.relationship.title}
</ThemedText>
<ThemedView style={styles.profileContainer}>
2024-10-14 13:48:22 -05:00
{user && (
<ThemedView style={styles.profileWrapper}>
<Image
2024-10-14 13:48:22 -05:00
source={{ uri: `${process.env.EXPO_PUBLIC_URL}${user.pfpURL}` }}
style={styles.profilePicture}
/>
2024-10-14 13:48:22 -05:00
<ThemedText style={styles.name}>
{user.fullName.split(' ')[0]}
</ThemedText>
</ThemedView>
)}
{status.partner && (
<ThemedView style={styles.profileWrapper}>
<Image
2024-10-14 13:48:22 -05:00
source={{ uri: `${process.env.EXPO_PUBLIC_URL}` +
`${status.partner.pfpURL}` }}
style={styles.profilePicture}
/>
2024-10-14 13:48:22 -05:00
<ThemedText style={styles.name}>
{status.partner.fullName.split(' ')[0]}
</ThemedText>
</ThemedView>
)}
</ThemedView>
</>
);
}
};
2024-10-11 13:46:46 -05:00
return (
<ThemedView style={styles.container}>
{renderRelationshipContent()}
2024-10-11 13:46:46 -05:00
</ThemedView>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
},
title: {
fontSize: 24,
fontWeight: 'bold',
marginBottom: 20,
},
profileContainer: {
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
marginTop: 20,
},
profileWrapper: {
alignItems: 'center',
marginHorizontal: 10,
},
profilePicture: {
width: 100,
height: 100,
borderRadius: 50,
marginBottom: 10,
},
name: {
fontSize: 12,
fontWeight: 'bold',
},
buttonLabel: {
2024-10-11 13:46:46 -05:00
fontSize: 16,
},
lastChecked: {
fontSize: 12,
marginBottom: 10,
},
buttonContainer: {
flexDirection: 'row',
justifyContent: 'space-around',
width: '100%',
marginTop: 20,
},
2024-10-11 13:46:46 -05:00
});
export default Relationships;