/// <reference path="./Measure.js"/>

global.MarginMeasure = function MarginMeasure(margin) {
    if (!margin)
        margin = Measure.zero();
    
    this.left = this._get(margin.left ? margin.left : margin),
    this.right = this._get(margin.right ? margin.right : margin),
    this.top = this._get(margin.top ? margin.top : margin),
    this.bottom = this._get(margin.bottom ? margin.bottom : margin);
};

MarginMeasure.prototype = {
    inflate: function (margin) {
        if (!margin)
            margin = Measure.zero();

        var newMargin = new MarginMeasure();
        newMargin.left = this._add(this.left, margin.left ? margin.left : margin),
        newMargin.right = this._add(this.right, margin.right ? margin.right : margin),
        newMargin.top = this._add(this.top, margin.top ? margin.top : margin),
        newMargin.bottom = this._add(this.bottom, margin.bottom ? margin.bottom : margin);

        return newMargin;
    },

    toInches: function () {
        return this._select(function (measure) { return measure.toInches(); });
    },

    _select: function (predicate) {
        return {
            left: predicate(this.left),
            right: predicate(this.right),
            top: predicate(this.top),
            bottom: predicate(this.bottom)
        };
    },
        
    _get: function (a) {
        if (a instanceof Measure)
            return a;

        if (typeof a === 'number')
            return Measure.fromPoints(a);

        return Measure.zero();
    },

    _add: function (a, b) {
        if (b instanceof Measure)
            return a.add(b);

        if (typeof b === 'number')
            return a.addPoints(b);

        return a;
    }
};
