override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
currentUserKey = DataService.ds.REF_CURRENT_USER.key
DataService.ds.REF_CURRENT_USER.observeSingleEventOfType(.Value, withBlock: { snapshot in
if let matchesInterestedIn = snapshot.value["matchesInterestedIn"] {
if matchesInterestedIn != nil {
for (_, value) in matchesInterestedIn as! [String: String] {
self.currentUserInterests.append(value)
}
}
}
})
DataService.ds.REF_USERS.observeSingleEventOfType(.Value, withBlock: { snapshot in
self.admirers = [Match]()
self.matches = [Match]()
if snapshot != nil {
for potentialMatch in snapshot.children {
let potentialMatchData = potentialMatch.valueInExportFormat()
if potentialMatchData["matchesInterestedIn"] != nil {
if let potentialMatchInterests = potentialMatchData["matchesInterestedIn"] as? Dictionary<String, String> {
if potentialMatchInterests.values.contains(self.currentUserKey) {
let interestedMatch = Match(snapshot: potentialMatch as! FDataSnapshot)
self.admirers.append(interestedMatch)
}
}
}
}
}
if self.admirers.count > 0 {
for potentialMatch in self.admirers {
if self.currentUserInterests.contains(potentialMatch.key) {
self.matches.append(potentialMatch)
let chatRoomInitializer = ["user1": self.currentUserKey, "user2": potentialMatch.key]
let chatRoomRef = DataService.ds.REF_CHATROOMS.childByAutoId()
let chatRoomID = chatRoomRef.key
// For some odd reason, the next two lines of code create an endless amount of chatroom objects from the base reference
let currentUserChatRoomRef = DataService.ds.REF_CURRENT_USER.childByAppendingPath("chatrooms").childByAutoId()
currentUserChatRoomRef.setValue(chatRoomID)
let potentialMatchRef = DataService.ds.REF_USERS.childByAppendingPath(potentialMatch.key).childByAppendingPath("chatrooms").childByAutoId()
potentialMatchRef.setValue(chatRoomRef.key)
chatRoomRef.setValue(chatRoomInitializer)
}
}
}
self.tableView.reloadData()
})
}