package time;

public class Time implements Comparable<Time> {

    protected final static int SECOND = 100;
    protected final static int MINUTE = 60 * SECOND;
    protected final static int HOUR   = 60 * MINUTE;

    protected int hour;
    protected int minute;
    protected int second;
    protected int milisecond;
    protected int value;

    public int getHour() { return hour; }
    public int getMinute() { return minute; }
    public int getSecond() { return second; }
    public int getMilisecond() { return milisecond; }
    public int getRawValue() { return value; }

    private Time(int h, int m, int s, int ms) {
        hour       = h;
        minute     = m;
        second     = s;
        milisecond = ms;
        value      = hour * HOUR + minute * MINUTE + second * SECOND + milisecond;
    }

    private Time(int v) {
        hour       = v / HOUR;
        minute     = (v % HOUR) / MINUTE;
        second     = (v % MINUTE) / SECOND;
        milisecond = v % SECOND;
        value      = v;
    }

    public Time(Time t) {
        hour       = t.hour;
        minute     = t.minute;
        second     = t.second;
        milisecond = t.milisecond;
        value      = t.value;
    }

    public static Time makeTime(String str) {
       try {
           String[] x = str.split("[:.]");
           int h  = Integer.parseInt(x[0]);
           int m  = Integer.parseInt(x[1]);
           int s  = Integer.parseInt(x[2]);
           int ms = Integer.parseInt(x[3]);
           return
             ((0 <= h && h <= 23) && (0 <= m  && m  <= 59) &&
              (0 <= s && s <= 59) && (0 <= ms && ms <= 999))
             ? new Time(h, m, s, ms) : null;
       }
       catch (RuntimeException e) {
           return null;
       }
    }

    public static Time diffTime(Time t1, Time t2) {
        return new Time(Math.abs(t1.value - t2.value));
    }

    @Override
    public boolean equals(Object o) {
        if (o instanceof Time) {
            Time t = (Time) o;
            return (t.value == this.value);
        }
        return false;
    }

    @Override
    public int hashCode() {
        return value;
    }

    @Override
    public String toString() {
        return String.format("%02d:%02d:%02d.%03d", hour, minute, second,
          milisecond);
    }

    public int compareTo(Time t) {
        return (this.value - t.value);
    }
}
