package com.jscape.util;

import static com.jscape.util.Parameters.assertNotNull;

/**
 * @author Alex Usun
 */
public class BitRate
        implements Comparable<BitRate> {

    public final long value;
    public final Unit unit;

    public static BitRate bitps(long value) {
        return new BitRate(value, Unit.BIT_PER_SECOND);
    }

    public static BitRate kbitps(long value) {
        return new BitRate(value, Unit.KBIT_PER_SECOND);
    }

    public static BitRate mbitps(long value) {
        return new BitRate(value, Unit.MBIT_PER_SECOND);
    }

    public static BitRate gbitps(long value) {
        return new BitRate(value, Unit.GBIT_PER_SECOND);
    }

    public BitRate(long value, Unit unit) {
        this.value = value;

        assertNotNull(unit);
        this.unit = unit;
    }

    public long toBitps() {
        return this.value * this.unit.factor;
    }

    public int compareTo(BitRate that) {
        long thisBitps = toBitps();
        long thatBitps = that.toBitps();

        return thisBitps < thatBitps ? -1 : thisBitps == thatBitps ? 0 : 1;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }

        BitRate that = (BitRate) o;

        return compareTo(that) == 0;
    }

    @Override
    public int hashCode() {
        int result = (int) (this.value ^ (this.value >>> 32));
        result = 31 * result + unit.hashCode();
        return result;
    }

    @Override
    public String toString() {
        return "BitRate {"
                + "value=" + this.value
                + ", unit=" + this.unit
                + '}';
    }

    public enum Unit {

        BIT_PER_SECOND(1L),
        KBIT_PER_SECOND(1000L),
        MBIT_PER_SECOND(1000000L),
        GBIT_PER_SECOND(1000000000L);

        public final long factor;

        Unit(long factor) {
            this.factor = factor;
        }


    }
}
