package jp.sourceforge.nicoro;

import android.os.Parcel;
import android.os.Parcelable;

/**
 * rational number, fraction
 */
public class Rational implements Parcelable, Comparable<Rational> {
	/**
	 * numerator （分子）<br>
	 * 値が大きくなりかねないのでlongに
	 */
	public long num;
	/**
	 * denominator （分母）
	 */
	public int den;

	public Rational() {
		num = 0;
		den = 1;
	}

	public Rational(long n, int d) {
		num = n;
		den = d;
	}

	public float getDivideFloat() {
		if (den == 0) {
			return 0;
		}
		return (float) ((double) num / den);
	}
	public int getDivideInt() {
		if (den == 0) {
			return 0;
		}
		return (int) (num / den);
	}

	/**
	 * 分数が秒を表しているものとして、ミリ秒単位に変換して取得
	 * @return
	 */
	public int getMs() {
		if (den == 0) {
			return 0;
		}
		return (int) (num * 1000L / den);
	}

	/**
	 * 分数が秒を表しているものとして、10ミリ秒単位に変換して取得
	 * @return
	 */
	public int getVpos() {
		if (den == 0) {
			return 0;
		}
		return (int) (num * 100L / den);
	}

	// Parcelable

	@Override
	public int describeContents() {
		return 0;
	}

	@Override
	public void writeToParcel(Parcel dest, int flags) {
		dest.writeLong(num);
		dest.writeInt(den);
	}

	public static final Parcelable.Creator<Rational> CREATOR =
		new Parcelable.Creator<Rational>() {
			@Override
			public Rational createFromParcel(Parcel source) {
				return new Rational(source);
			}

			@Override
			public Rational[] newArray(int size) {
				return new Rational[size];
			}

	};

	Rational(Parcel p) {
		num = p.readLong();
		den = p.readInt();
	}

	@Override
	public boolean equals(Object o) {
	    if (this == o) {
	        return true;
	    }
	    if (!(o instanceof Rational)) {
	        return false;
	    }
	    Rational another = (Rational) o;
	    return num == another.num && den == another.den;
	}

	@Override
	public int hashCode() {
	    return (int) (num / den);
	}

	// Comparable

    @Override
    public int compareTo(Rational another) {
        long diff = num / den - another.num / another.den;
        if (diff > 0) {
            return 1;
        } else if (diff == 0) {
            return 0;
        } else {
            return -1;
        }
    }
}
