313 lines
9.4 KiB
TypeScript
313 lines
9.4 KiB
TypeScript
import React, { useEffect, useState } from 'react';
|
|
import { Image, StyleSheet, AppState } from 'react-native';
|
|
import { ThemedView } from '@/components/ThemedView';
|
|
import { ThemedText } from '@/components/ThemedText';
|
|
import { getUserData } from '@/components/services/securestorage/UserData';
|
|
import { saveRelationshipData, getRelationshipData } from '@/components/services/securestorage/RelationshipData';
|
|
import Button from '@/components/buttons/Button';
|
|
import { Colors } from '@/constants/Colors';
|
|
import { useColorScheme } from '@/hooks/useColorScheme';
|
|
import RequestRelationship from '@/components/home/RequestRelationship';
|
|
|
|
type UserData = {
|
|
id: number;
|
|
appleId: string | null;
|
|
appleEmail: string | null;
|
|
fullName: string;
|
|
pfpURL: string | null;
|
|
pushToken: string;
|
|
createdAt: Date;
|
|
};
|
|
|
|
type Relationship = {
|
|
id: number;
|
|
title: string;
|
|
status: 'pending' | 'accepted' | 'rejected';
|
|
relationshipStartDate: Date;
|
|
createdAt: Date;
|
|
};
|
|
|
|
type RelationshipData = {
|
|
relationship: Relationship;
|
|
partner: UserData;
|
|
};
|
|
|
|
type RelationshipProps = {
|
|
profilePictureUrl: string | null;
|
|
};
|
|
|
|
const Relationships: React.FC<RelationshipProps> = ({ profilePictureUrl }) => {
|
|
const scheme = useColorScheme() ?? 'light';
|
|
const [status, setStatus] = useState<RelationshipData | null>(null);
|
|
const [userData, setUserData] = useState<UserData | null>(null);
|
|
const [showRequestRelationship, setShowRequestRelationship] = useState(false);
|
|
const [loading, setLoading] = useState(true);
|
|
|
|
const handleRequestSent = (data: RelationshipData) => {
|
|
setStatus(data);
|
|
setShowRequestRelationship(false);
|
|
};
|
|
|
|
useEffect(() => {
|
|
fetchRelationshipStatus();
|
|
setupPeriodicCheck();
|
|
}, []);
|
|
|
|
useEffect(() => {
|
|
if (profilePictureUrl && userData) {
|
|
setUserData(prevData => prevData ? {...prevData, pfpURL: profilePictureUrl} : null);
|
|
}
|
|
}, [profilePictureUrl]);
|
|
|
|
const setupPeriodicCheck = () => {
|
|
let intervalId: NodeJS.Timeout | null = null;
|
|
|
|
const startChecking = () => {
|
|
checkRelationshipStatus();
|
|
intervalId = setInterval(checkRelationshipStatus, 600000); //
|
|
};
|
|
|
|
const stopChecking = () => {
|
|
if (intervalId) {
|
|
clearInterval(intervalId);
|
|
intervalId = null;
|
|
}
|
|
};
|
|
|
|
const handleAppStateChange = (nextAppState: string) => {
|
|
if (nextAppState === 'active') {
|
|
startChecking();
|
|
} else {
|
|
stopChecking();
|
|
}
|
|
};
|
|
|
|
const subscription = AppState.addEventListener('change', handleAppStateChange);
|
|
|
|
if (AppState.currentState === 'active') {
|
|
startChecking();
|
|
}
|
|
|
|
return () => {
|
|
stopChecking();
|
|
subscription.remove();
|
|
};
|
|
};
|
|
|
|
const fetchRelationshipStatus = async () => {
|
|
setLoading(true);
|
|
try {
|
|
const userDataFromStorage: UserData = await getUserData() as UserData;
|
|
if (!userDataFromStorage || !userDataFromStorage.id) {
|
|
throw new Error('User data not found');
|
|
}
|
|
setUserData(userDataFromStorage);
|
|
|
|
// First, try to get relationship data from SecureStore
|
|
const storedRelationshipData = await getRelationshipData();
|
|
if (storedRelationshipData) {
|
|
setStatus(storedRelationshipData);
|
|
}
|
|
|
|
// Then, fetch the latest data from the API
|
|
await checkRelationshipStatus();
|
|
} catch (error) {
|
|
console.log('Error fetching relationship status:', error);
|
|
} finally {
|
|
setLoading(false);
|
|
}
|
|
};
|
|
|
|
const checkRelationshipStatus = async () => {
|
|
try {
|
|
const userDataFromStorage: UserData = await getUserData() as UserData;
|
|
if (!userDataFromStorage || !userDataFromStorage.id) {
|
|
throw new Error('User data not found');
|
|
}
|
|
|
|
const response = await fetch(`${process.env.EXPO_PUBLIC_API_URL}/relationships/getRelationshipData?userId=${userDataFromStorage.id}`, {
|
|
headers: {
|
|
'x-api-key': process.env.EXPO_PUBLIC_API_KEY ?? '',
|
|
},
|
|
});
|
|
|
|
if (!response.ok) {
|
|
const errorData = await response.json();
|
|
throw new Error(errorData.message || `HTTP error! status: ${response.status}`);
|
|
}
|
|
const data = await response.json() as RelationshipData;
|
|
setStatus(data);
|
|
await saveRelationshipData(data);
|
|
} catch (error) {
|
|
console.log('No relationship found or error checking status:', error);
|
|
setStatus(null);
|
|
} finally {
|
|
}
|
|
};
|
|
|
|
const handleUpdateRelationshipStatus = async (newStatus: 'accepted' | 'rejected') => {
|
|
if (!status || !status.relationship) {
|
|
console.error('No relationship to update');
|
|
return;
|
|
}
|
|
try {
|
|
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();
|
|
throw new Error(errorData.message || `HTTP error! status: ${response.status}`);
|
|
}
|
|
|
|
const result = await response.json();
|
|
if (result) {
|
|
// Refresh the relationship status
|
|
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');
|
|
|
|
if (loading) {
|
|
return <ThemedText>Loading...</ThemedText>;
|
|
}
|
|
const renderRelationshipContent = () => {
|
|
if (!status || !status.relationship) {
|
|
// Case 1: Not in a relationship
|
|
return showRequestRelationship ? (
|
|
<RequestRelationship onRequestSent={handleRequestSent} />
|
|
) : (
|
|
<Button width={220} height={60} onPress={() => setShowRequestRelationship(true)}>
|
|
<ThemedText style={[styles.buttonLabel, {color: Colors[scheme].background}]}>
|
|
Request Relationship
|
|
</ThemedText>
|
|
</Button>
|
|
);
|
|
} else if (status.relationship.status === 'pending') {
|
|
// Case 2 & 3: Pending relationship (we can't differentiate who requested it)
|
|
return (
|
|
<>
|
|
<ThemedText style={styles.title}>Pending Relationship</ThemedText>
|
|
<ThemedView style={styles.profileContainer}>
|
|
<ThemedView style={styles.profileWrapper}>
|
|
<Image
|
|
source={{ uri: `${process.env.EXPO_PUBLIC_URL}${status.partner.pfpURL}` }}
|
|
style={styles.profilePicture}
|
|
/>
|
|
<ThemedText style={styles.name}>{status.partner.fullName}</ThemedText>
|
|
</ThemedView>
|
|
</ThemedView>
|
|
<ThemedView style={styles.buttonContainer}>
|
|
<Button width={100} height={40} onPress={handleAcceptRequest}>
|
|
<ThemedText style={[styles.buttonLabel, {color: Colors[scheme].background}]}>
|
|
Accept
|
|
</ThemedText>
|
|
</Button>
|
|
<Button width={100} height={40} onPress={handleRejectRequest}>
|
|
<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 (
|
|
<>
|
|
<ThemedText style={styles.title}>{status.relationship.title}</ThemedText>
|
|
<ThemedView style={styles.profileContainer}>
|
|
{userData && (
|
|
<ThemedView style={styles.profileWrapper}>
|
|
<Image
|
|
source={{ uri: `${process.env.EXPO_PUBLIC_URL}${userData.pfpURL}` }}
|
|
style={styles.profilePicture}
|
|
/>
|
|
<ThemedText style={styles.name}>{userData.fullName.split(' ')[0]}</ThemedText>
|
|
</ThemedView>
|
|
)}
|
|
{status.partner && (
|
|
<ThemedView style={styles.profileWrapper}>
|
|
<Image
|
|
source={{ uri: `${process.env.EXPO_PUBLIC_URL}${status.partner.pfpURL}` }}
|
|
style={styles.profilePicture}
|
|
/>
|
|
<ThemedText style={styles.name}>{status.partner.fullName.split(' ')[0]}</ThemedText>
|
|
</ThemedView>
|
|
)}
|
|
</ThemedView>
|
|
</>
|
|
);
|
|
}
|
|
};
|
|
|
|
return (
|
|
<ThemedView style={styles.container}>
|
|
{renderRelationshipContent()}
|
|
</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: {
|
|
fontSize: 16,
|
|
},
|
|
lastChecked: {
|
|
fontSize: 12,
|
|
marginBottom: 10,
|
|
},
|
|
buttonContainer: {
|
|
flexDirection: 'row',
|
|
justifyContent: 'space-around',
|
|
width: '100%',
|
|
marginTop: 20,
|
|
},
|
|
});
|
|
|
|
export default Relationships;
|