module main;

import std.random;
import siege;

final uint Width = 640;
final uint Height = 480;

// these will be generic functions if/when those are added

// void swap(T)(ref T a, ref T b);
void swap(ref float a, ref float b)
{
    float tmp = a;
    a = b;
    b = tmp;
}
// T clamp(T,A,B)(T x, A a, B b);
float clamp(float x, float a, float b)
{
    if(b < a)
        swap(a, b);

    if(x < a)
        return a;
    if(b < x)
        return b;
    return x;
}
// bool inRange(T,A,B)(T x, A a, B b);
bool inRange(float x, float a, float b)
{
    if(b < a)
        swap(a, b);

    if(x < a)
        return false;
    if(b < x)
        return false;
    return true;
}

class Box: Entity
{
    float x, y;     // position
    float size;     // box size
    float xv = 1;   // x velocity
    float yv = 1;   // y velocity
    this(float x, float y, float size = 32)
    {
        this.x = x;
        this.y = y;
        this.size = size;
    }

    void bounce(bool x, bool y)
    {
        if(x)
            xv = -xv;
        if(y)
            yv = -yv;
    }
    void bounceEdge()
    {
        if(!inRange(x, size / 2, Width - size / 2))
        {
            x = clamp(x, size / 2, Width - size / 2);
            bounce(true, false);
        }
        if(!inRange(y, size / 2, Height - size / 2))
        {
            y = clamp(y, size / 2, Height - size / 2);
            bounce(false, true);
        }
    }

    void evTick()
    {
        x += xv;
        y += yv;
        bounceEdge();
    }
    void evDraw()
    {
        sgDrawColor4f(0.00, 0.50, 0.75, 0.75);
        sgDrawRectangleWH(x - size / 2, y - size / 2, size, size, SG_TRUE);
        sgDrawColor4f(0.00, 0.75, 1.00, 1.00);
        sgDrawRectangleWH(x - size / 2, y - size / 2, size, size, SG_FALSE);
    }
}

int main()
{
    window.open(Width, Height);

    float xr = rand(16.0, Width - 16.0);
    float yr = rand(16.0, Height - 16.0);
    Box box = new Box(xr, yr);

    return core.run();
}