Skip to content

Instantly share code, notes, and snippets.

@usbportnoy
Last active September 30, 2016 02:36
Show Gist options
  • Save usbportnoy/20998fa501a8c427c4e215de9ff0ee4a to your computer and use it in GitHub Desktop.
Save usbportnoy/20998fa501a8c427c4e215de9ff0ee4a to your computer and use it in GitHub Desktop.
package com.dkary.portj.danichat.fragments.profile;
import java.util.Calendar;
import java.util.Date;
public class OnlineStatus {
public enum States {Unknown, Online, Distant, Recent, Offline;}
private int recentOnlineThresholdDays;
private int onlineThresholdHrs;
private int distantOnlineThresholdWeeks;
public OnlineStatus() {
}
public OnlineStatus(int recentOnlineThresholdDays, int onlineThresholdHrs, int distantOnlineThresholdWeeks) {
this.recentOnlineThresholdDays = recentOnlineThresholdDays;
this.onlineThresholdHrs = onlineThresholdHrs;
this.distantOnlineThresholdWeeks = distantOnlineThresholdWeeks;
}
public void setOnlineThresholdHrs(int hours) {
this.onlineThresholdHrs = hours;
}
public void setRecentOnlineThresholdDays(int days) {
this.recentOnlineThresholdDays = days;
}
public void setDistantOnlineThresholdWeeks(int weeks) {
this.distantOnlineThresholdWeeks = weeks;
}
public States getStatus(Date lastOnline, Calendar calendar) {
if (onlineThresholdHrs <= 0) {
throw new IllegalArgumentException("Requires online threshold in hours");
}
if (recentOnlineThresholdDays <= 0) {
throw new IllegalArgumentException("Requires online threshold in days");
}
if (distantOnlineThresholdWeeks <= 0) {
throw new IllegalArgumentException("Requires online threshold in weeks");
}
int currentHour = calendar.get(Calendar.HOUR_OF_DAY);
int currentDay = calendar.get(Calendar.DAY_OF_YEAR);
int currentWeek = calendar.get(Calendar.WEEK_OF_YEAR);
States state = States.Offline;
if (hitsThreshold(
Calendar.WEEK_OF_YEAR,
currentWeek - distantOnlineThresholdWeeks,
lastOnline)) {
state = States.Distant;
}
if (hitsThreshold(
Calendar.DAY_OF_YEAR,
currentDay - recentOnlineThresholdDays,
lastOnline)) {
state = States.Recent;
}
if (hitsThreshold(
Calendar.HOUR_OF_DAY,
currentHour - onlineThresholdHrs,
lastOnline)) {
state = States.Online;
}
return state;
}
private boolean hitsThreshold(int calenderField, int value, Date time) {
Calendar calendar = Calendar.getInstance();
calendar.set(
calenderField,
value
);
Date threshold = calendar.getTime();
return time.after(threshold);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment