package main.java;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
import com.firebase.client.ChildEventListener;
import com.firebase.client.DataSnapshot;
import com.firebase.client.Firebase;
public class ContactSearch {
private HashMap<Long, User> users;
public ContactSearch(HashMap<Long, User> users) {
this.users = users;
}
public void contactSearch(){
String url = "https://signal-app.firebaseio.com/contact-search/";
Firebase dataRef = new Firebase(url);
dataRef.addChildEventListener(new ChildEventListener() {
@Override
public void onChildChanged(DataSnapshot snapshot, String previousChildName) {
}
@Override
public void onCancelled() {
System.err.println("Listener was cancelled");
}
@Override
public void onChildAdded(DataSnapshot snapshot, String arg1) {
String requestID = snapshot.getName();
String snapShotNumbers = (String) snapshot.getValue();
(new Thread(new ContactsComparator(new HashSet<Long>(users.keySet()), snapShotNumbers, requestID))).start();
}
@Override
public void onChildMoved(DataSnapshot arg0, String arg1) {
// TODO Auto-generated method stub
}
@Override
public void onChildRemoved(DataSnapshot arg0) {
// TODO Auto-generated method stub
}
});
}
// A thread that compares the numbers received with the actually
// registered numbers.
private class ContactsComparator implements Runnable{
Set<Long> userNums;
String snapShotNumbers;
String requestID;
public ContactsComparator(Set<Long> userNums, String snapShotNumbers, String requestID){
this.userNums = userNums;
this.snapShotNumbers = snapShotNumbers;
this.requestID = requestID;
}
// does the comparison between the comma-separated snapShotNumbers and the
// actually registered numbers, and updates the entry in Firebase
public void run(){
String result = "";
String[] numberArr = snapShotNumbers.split(",");
for(String num : numberArr){
try{
long n = Long.parseLong(num);
if(userNums.contains(n)){
result += n + ",";
}
} catch (NumberFormatException e){
System.err.println("Not A Number In Contact Search: " + num);
}
}
if(result.length() != 0){
result = result.substring(0, result.length() - 1);
}
updateContactSearch(result, requestID);
}
// with the updated phone numbers, this method updates the
// entry from the requester.
private void updateContactSearch(String result, String request){
String url = "https://signal-app.firebaseio.com/contact-search/";
Firebase dataRef = new Firebase(url);
dataRef.child(request).setValue(result);
}
}
}