package com.sourcefellows.patterns.composite;

public class Weight {

    public enum Unit {
        MILLIGRAMS(1),
        GRAMS(1000),
        KILOGRAM(1000 * 1000),
        TONS(1000 * 1000 * 1000);

        private final int milligrams;

        Unit(int i) {
            this.milligrams = i;
        }
    }

    private final int weightInMilligrams;

    private Weight(int weightInMilligrams) {
        this.weightInMilligrams = weightInMilligrams;
    }

    public static Weight createWeight(int weight, Unit unit) {
        return new Weight(weight * unit.milligrams);
    }

    public static Weight sum(Weight lha, Weight rha) {
        return new Weight(lha.weightInMilligrams + rha.weightInMilligrams);
    }

    @Override
    public String toString() {

        if (weightInMilligrams > Unit.TONS.milligrams) {
            return String.format("%d tons", weightInMilligrams /Unit.TONS.milligrams);
        }

        if (weightInMilligrams > Unit.KILOGRAM.milligrams) {
            return String.format("%d kg", weightInMilligrams /Unit.KILOGRAM.milligrams);
        }

        if (weightInMilligrams > Unit.GRAMS.milligrams) {
            return String.format("%d g", weightInMilligrams /Unit.GRAMS.milligrams);
        }

        return String.format("%d mg", weightInMilligrams);
    }
}
