aboutsummaryrefslogtreecommitdiffstats
path: root/src/eu/siacs/conversations/entities/Presences.java
blob: 9a22e559c230eaba3da28362edbde788060bed17 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package eu.siacs.conversations.entities;

import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map.Entry;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import eu.siacs.conversations.xml.Element;

public class Presences {

	public static final int CHAT = -1;
	public static final int ONLINE = 0;
	public static final int AWAY = 1;
	public static final int XA = 2;
	public static final int DND = 3;
	public static final int OFFLINE = 4;
	
	private Hashtable<String, Integer> presences = new Hashtable<String, Integer>();

	public Hashtable<String, Integer> getPresences() {
		return this.presences;
	}

	public void updatePresence(String resource, int status) {
		this.presences.put(resource, status);
	}

	public void removePresence(String resource) {
		this.presences.remove(resource);
	}
	
	public int getMostAvailableStatus() {
		int status = OFFLINE;
		Iterator<Entry<String, Integer>> it = presences.entrySet().iterator();
		while (it.hasNext()) {
			Entry<String, Integer> entry = it.next();
			if (entry.getValue()<status) status = entry.getValue();
		}
		return status;
	}

	public String toJsonString() {
		JSONArray json = new JSONArray();
		Iterator<Entry<String, Integer>> it = presences.entrySet().iterator();

		while (it.hasNext()) {
			Entry<String, Integer> entry = it.next();
			JSONObject jObj = new JSONObject();
			try {
				jObj.put("resource", entry.getKey());
				jObj.put("status", entry.getValue());
			} catch (JSONException e) {

			}
			json.put(jObj);
		}
		return json.toString();
	}

	public static Presences fromJsonString(String jsonString) {
		Presences presences = new Presences();
		try {
			JSONArray json = new JSONArray(jsonString);
			for (int i = 0; i < json.length(); ++i) {
				JSONObject jObj = json.getJSONObject(i);
				presences.updatePresence(jObj.getString("resource"),
						jObj.getInt("status"));
			}
		} catch (JSONException e1) {
			
		}
		return presences;
	}

	public static int parseShow(Element show) {
		if (show == null) {
			return Presences.ONLINE;
		} else if (show.getContent().equals("away")) {
			return Presences.AWAY;
		} else if (show.getContent().equals("xa")) {
			return Presences.XA;
		} else if (show.getContent().equals("chat")) {
			return Presences.CHAT;
		} else if (show.getContent().equals("dnd")) {
			return 	Presences.DND;
		} else {
			return Presences.OFFLINE;
		}
	}
	
	public int size() {
		return presences.size();
	}
}