#include "Button.h"

Button::Button (
    int _x, int _y, 
    int _imageWidth, 
    int _imageHeight,
    string imageUpFile, 
    string imageDownFile, 
    string imageUpMouseNearFile,
    string imageDownMouseNearFile
)
{
    x = _x;
    y = _y;
    imageWidth = _imageWidth; 
    imageHeight = _imageHeight;

    pushed = false;
    mouseNear = false;

    int size = imagesize (0, 0, imageWidth + 1, imageHeight + 1);

    imageDown = malloc (size);
    imageUp = malloc (size);
    imageDownMouseNear = malloc (size);
    imageUpMouseNear = malloc (size);

    readimagefile (imageUpFile.c_str (), 0, 0, imageWidth + 1, imageHeight + 1);
    getimage (0, 0, imageWidth + 1, imageHeight + 1, imageUp);

    readimagefile (imageDownFile.c_str (), 0, 0, imageWidth + 1, imageHeight + 1);
    getimage (0, 0, imageWidth + 1, imageHeight + 1, imageDown);

    readimagefile (imageUpMouseNearFile.c_str (), 0, 0, imageWidth + 1, imageHeight + 1);
    getimage (0, 0, imageWidth + 1, imageHeight + 1, imageUpMouseNear);

    readimagefile (imageDownMouseNearFile.c_str (), 0, 0, imageWidth + 1, imageHeight + 1);
    getimage (0, 0, imageWidth + 1, imageHeight + 1, imageDownMouseNear);
}

void Button::draw ()
{
    if (pushed)
        if (mouseNear)
            putimage (x, y, imageDownMouseNear, COPY_PUT );
        else
            putimage (x, y, imageDown, COPY_PUT );
    else
        if (mouseNear)
            putimage (x, y, imageUpMouseNear, COPY_PUT );
        else
            putimage (x, y, imageUp, COPY_PUT );
}

void Button::mouseDown (int mx, int my)
{
    if (nearBy (mx, my))
        pushed = !pushed;
}

void Button::mouseUp (int mx, int my)
{
    // nothing to do
}

void Button::mouseMove (int mx, int my)
{
    mouseNear = nearBy (mx, my);
}

bool Button::nearBy (int mx, int my)
{
    if (mx < x) return false;
    if (my < y) return false;
    if (mx > x + imageWidth) return false;
    if (my > y + imageHeight) return false;

    return true;
}
