var _global = this;

(function () {

// constructor
    
    function Renderer (canvas)
    {
        this._particleList  = {};
        
        this.reset(canvas);
    }
    
    _global.Renderer = Renderer;
    
// public

    Renderer.prototype.reset = function (canvas)
    {
        this._canvas    = canvas;
        this._context   = this._canvas.getContext("2d");
        
        this._width     = this._canvas.width;
        this._height    = this._canvas.height;
        
        this._context.globalCompositeOperation = "lighter";
        
        this._particleGradient  = this._context.createRadialGradient(
            0, 0,   // start center
            1,      // start circle radius
            0, 0,   // end circle center
            10      // end circle radius
        );
        
        this._particleGradient.addColorStop(0, "#2b80f3");    // center
        this._particleGradient.addColorStop(1, "rgba(126, 179, 250, 0)");    // outer edge
        
        this._context.fillStyle = this._particleGradient;
    };
    
    Renderer.prototype.addParticle = function (particle)
    {
        this._particleList[particle.id] = particle;
    };
    
    Renderer.prototype.removeParticle = function (particle)
    {
        delete this._particleList[particle.id];
    };
    
    Renderer.prototype.redraw = function ()
    {
        draw.call(this);
    };
    
// private

    function draw ()
    {
        // foreground
        this._context.clearRect(
            0, 0,                       // x, y
            this._width, this._height   // width, height
        );
        
        for (var id in this._particleList) {
            var particle        = this._particleList[id];
            var particleScale   = particle.mass;
            
            this._context.save();
            this._context.translate(particle.x, particle.y);
            
            var aScale = Math.sqrt(particle.xV * particle.xV + particle.yV * particle.yV);
            
            var xScale = Math.abs(0.05 * particle.xV);
            var yScale = Math.abs(0.05 * particle.yV);
            
            this._context.scale(
                particleScale + xScale,
                particleScale + yScale
            );
            
            this._context.globalAlpha = Math.max(1 - (aScale * 0.05), 0.7);
            this._context.fillRect(-10, -10, 20, 20);
            this._context.restore();
        }
    }
    
})();

