/* global Bjarnia */
Bjarnia.Button = new Object();

Bjarnia.Button.buttons = [];

Bjarnia.Button.add = function (x, y, width, height, text, handler) {
    var button = new Object();
    
    // Set properties on the button
    button.x = x;
    button.y = y;
    button.width = width;
    button.height = height;
    button.text = text;
    button.handler = handler;
    
    // Add the button to the buttons array
    Bjarnia.Button.buttons.push(button);
    
    // Return the button
    return button;
};

Bjarnia.Button.remove = function (button) {
    // Remove the button from the buttons array
    Bjarnia.Button.buttons.splice(Bjarnia.Button.buttons.indexOf(button), 1);
};

Bjarnia.Button.hitsButton = function (x, y, button) {
    if (x > button.x && x < button.x + button.width && y > button.y && y < button.y + button.height) {
        return true;
    }
    
    return false;
};

Bjarnia.Button.registerListeners = function () {
    Bjarnia.Component.gameCanvas.addEventListener('mousemove', function (e) {
        Bjarnia.Button.buttons.forEach(function (v, i) {
            if (Bjarnia.Button.hitsButton(Bjarnia.Component.normalizeX(e.clientX), Bjarnia.Component.normalizeY(e.clientY), v)) {
                v.hover = true;
            } else {
                v.hover = false;
            }
        });
    });
    
    Bjarnia.Component.gameCanvas.addEventListener('mousedown', function (e) {
        Bjarnia.Button.buttons.forEach(function (v, i) {
            if (Bjarnia.Button.hitsButton(Bjarnia.Component.normalizeX(e.clientX), Bjarnia.Component.normalizeY(e.clientY), v)) {
                v.active = true;
            }
        });
    });
    
    window.addEventListener('mouseup', function (e) {
        Bjarnia.Button.buttons.forEach(function (v, i) {
            v.active = false;
        });
    });
    
    // Trigger the button handler on click
    Bjarnia.Component.gameCanvas.addEventListener('click', function (e) {
        Bjarnia.Button.buttons.forEach(function (v, i) {
            if (Bjarnia.Button.hitsButton(Bjarnia.Component.normalizeX(e.clientX), Bjarnia.Component.normalizeY(e.clientY), v)) {
                v.handler();
            }
        });
    });
};

Bjarnia.Button.render = function (g) {
    Bjarnia.Button.buttons.forEach(function (v, i) {
        if (v.active) {
            g.fillStyle = "rgb(120, 120, 120)";
        } else if (v.hover) {
            g.fillStyle = "rgb(150, 150, 150)";
        } else {
            g.fillStyle = "rgb(140, 140, 140)";
        }
        g.fillRect(v.x, v.y, v.width, v.height);
        
        // White centered button text
        g.fillStyle = "rgb(255, 255, 255)";
        g.textAlign = "center";
        g.textBaseline = "middle";
        g.font = v.height / 1.5 + "px sans-serif";
        g.fillText(v.text, v.x + v.width / 2, v.y + v.height / 2, v.width / 1.1);
    });
};
