Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion FlatMate/Components/MatchRow.swift
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ struct MatchRow: View {
.scaledToFill()
.frame(width: 90, height: 90)
.clipShape(Circle())
} else if phase.error != nil {
} else if phase.error != nil || imageURL == "" {
// Display a placeholder if there's an error
Image(systemName: "person.fill")
.resizable()
Expand Down
2 changes: 1 addition & 1 deletion FlatMate/Components/MessageTitleRow.swift
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ struct TitleRow: View {
.aspectRatio(contentMode: .fill)
.frame(width: 50, height: 50)
.cornerRadius(50)
} else if phase.error != nil {
} else if phase.error != nil || imageURL == "" {
// Placeholder for error loading
Image(systemName: "person.fill")
.resizable()
Expand Down
160 changes: 37 additions & 123 deletions FlatMate/Models/MatchModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -5,155 +5,69 @@
// Created by Youssef Abdelrhafour on 2024-11-17.
//

import Foundation
import Firebase
import FirebaseAuth
import Foundation

struct Match: Identifiable {
let id: String
let name: String
let imageURL: String
var chatID: String?
//let messagePreview: String? // Later iteration


static func fetchMatches(completion: @escaping ([Match]) -> Void) {
guard let currentUserID = Auth.auth().currentUser?.uid else {
print("Error: No authenticated user found.")
completion([]) // Return an empty array if the user is not logged in
completion([])
return
}

let db = Firestore.firestore()
let matchesCollection = db.collection("matches")
let usersCollection = db.collection("users")
var matchIDs: [String] = []
var matches: [Match] = []

let dispatchGroup = DispatchGroup()
var matches: [Match] = []

// Query the matches collection to find documents where currentUserID is involved
matchesCollection
.whereField("user1", isEqualTo: currentUserID)
.getDocuments { snapshot, error in
if let error = error {
print("Error fetching matches for user1: \(error)")
completion([])
return
}

snapshot?.documents.forEach { document in
if let user2 = document.data()["user2"] as? String {
matchIDs.append(user2) // Add the other user
}
}

// Query the other way (currentUserID as user2)
matchesCollection
.whereField("user2", isEqualTo: currentUserID)
.getDocuments { snapshot, error in
if let error = error {
print("Error fetching matches for user2: \(error)")
completion([])
return
}

snapshot?.documents.forEach { document in
if let user1 = document.data()["user1"] as? String {
matchIDs.append(user1) // Add the other user
}
}

// Remove duplicates from matchIDs
matchIDs = Array(Set(matchIDs))

// Fetch user details for each matchID
for matchID in matchIDs {
dispatchGroup.enter()

usersCollection.document(matchID).getDocument(source: .default) { snapshot, error in
if let error = error {
print("Error fetching user data: \(error)")
dispatchGroup.leave()
return
}

guard let data = snapshot?.data(),
let name = data["firstName"] as? String,
let profilePictureURL = data["profileImageURL"] as? String else {
print("Data missing or in incorrect format for matchID: \(matchID)")
dispatchGroup.leave()
return
}

// Fetch or create chatID
fetchChatID(user1: currentUserID, user2: matchID) { chatID in
let match = Match(
id: matchID,
name: name,
imageURL: profilePictureURL,
chatID: chatID
)

matches.append(match)
dispatchGroup.leave()
}
}
}

// Notify when all user data has been fetched
dispatchGroup.notify(queue: .main) {
completion(matches)
}
}
}
}
// Query for matches where user is either user1 or user2
let matchesQuery = matchesCollection.whereFilter(Filter.orFilter([
Filter.whereField("user1", isEqualTo: currentUserID),
Filter.whereField("user2", isEqualTo: currentUserID),
]))

dispatchGroup.enter()
matchesQuery.getDocuments { snapshot, error in
defer { dispatchGroup.leave() }

static func fetchChatID(user1: String, user2: String, completion: @escaping (String?) -> Void) {
let db = Firestore.firestore()
let chatCollection = db.collection("chats")

// Query to check if chatID exists
let chatID = [user1, user2].sorted().joined(separator: "_")
let chatDocRef = chatCollection.document(chatID)

chatDocRef.getDocument { document, error in
if let error = error {
print("Error checking chatID existence: \(error)")
completion(nil)
print("Error fetching matches: \(error)")
return
}

if let document = document, document.exists {
print("Found existing chatID: \(chatID)")
completion(chatID)
} else {
print("ChatID does not exist. Creating a new one.")
createChatID(user1: user1, user2: user2, completion: completion)

print("Query results:")
for document in snapshot?.documents ?? [] {
print(document.data())
let matchData = document.data()
// If currentUserID is user1, otherUser is user2, else otherUser is user1
let otherUserID = matchData["user1"] as! String == currentUserID ? matchData["user2"] as! String : matchData["user1"] as! String

dispatchGroup.enter()
usersCollection.document(otherUserID).getDocument { userSnapshot, _ in
defer { dispatchGroup.leave() }

if let userData = userSnapshot?.data(),
let name = userData["firstName"] as? String
{
let imageURL = userData["profileImageURL"] as? String
let match = Match(id: otherUserID, name: name, imageURL: imageURL ?? "")
matches.append(match)
}
}
}
}
}



private static func createChatID(user1: String, user2: String, completion: @escaping (String?) -> Void) {
let db = Firestore.firestore()
let chatCollection = db.collection("chats")

let chatData: [String: Any] = [
"users": [user1, user2],
"createdAt": FieldValue.serverTimestamp()
]

let chatID = [user1, user2].sorted().joined(separator: "_")
let chatRef = chatCollection.document(chatID)
chatRef.setData(chatData) { error in
if let error = error {
print("Error creating chatID: \(error)")
completion(nil)
} else {
completion(chatID)
}

dispatchGroup.notify(queue: .main) {
completion(matches)
}
print("Created new chatID: \(chatID)")
}
}
Loading