/**
 * Created by K_A_Volchica on 19.03.2015.
 */
import java.math.BigDecimal;

public class Money {
        private BigDecimal amount;
        private Currency currency;

    public Money(BigDecimal amount, Currency currency) {
        this.amount = amount;
        this.currency = currency;
    }

    public Money(String amount, Currency currency) {
        this(new BigDecimal(amount), currency);
    }

    public BigDecimal getAmount() {
        return amount;
    }

    public void setAmount(BigDecimal amount) {
        this.amount = amount;
    }

    public Currency getCurrency() {
        return currency;
    }

    public void setCurrency(Currency currency) {
        this.currency = currency;
    }

    @Override
    public String toString() {
        return amount + " " + currency;
    }

    public Money add(Money m2) {
        BigDecimal m2amount = m2.amount;
        if (this.currency != m2.currency) {
            // throw new IllegalArgumentException("Cannot convert currency");
            m2amount = convert(m2amount, m2.currency, this.currency);
        }

        BigDecimal sum = this.amount.add(m2amount);
        return new Money(sum, this.currency);
    }

    public Money subtract(Money m2) {
        BigDecimal m2amount = m2.amount;
        if (this.currency != m2.currency) {
            // throw new IllegalArgumentException("Cannot convert currency");
            m2amount = convert(m2amount, m2.currency, this.currency);
        }

        BigDecimal sum = this.amount.subtract(m2amount);
        return new Money(sum, this.currency);
    }

    public Money multiply (BigDecimal s) {
        BigDecimal sub = this.amount.multiply(s);
        return new Money (sub, this.currency);
    }
    public Money divide (BigDecimal s) {
        BigDecimal sub = this.amount.divide(s);
        return new Money(sub, this.currency);
    }


    private BigDecimal convert(BigDecimal amount,
                               Currency currency1, Currency currency2) {
        // 1. Сконвертировать amount в базовую валюту RUR
        BigDecimal result = amount.multiply(currency1.getRate());

        // 2. Сконвертировать получившуюся сумму в целевую валюту currency 2
        result = result.divide(currency2.getRate(), 2, BigDecimal.ROUND_HALF_EVEN);

        return result;
    }
}