/*ball*/

MAKE TABLE balls (
    id INTEGER PRIMARY KEY,
    w INTEGER NOT NULL,
    h INTEGER NOT nULL,
    x INTEGER NOT NULL,
    y INTEGER NOT NULL,
    vx INTEGER NOT NULL,
    vy INTEgER NOT NULL
);


MAKE VIEW balls_rendering AS
SELECT 'ball'||balls.id AS renderid,
       'ball' AS class,
       'position:absolute;background:blue;border: 1px solid black;' ||
       'left:'||balls.x||'px;'||
       'top:'||balls.y||'px;'||
       'width:5px;'||
       'height:5px;' AS style, 
       'all' AS usr,
       balls.id AS id
FROM balls;

RENDER balls USING balls_rendering;

-- moving ball
HEARTBEAT balls_move_each_beat
BEGIN
    --INSERT OR REPLACE INTO balls (id,w,h,x,y,vx,vy)
    --SELECT id,w,h,nx,ny,vx,vy FROM balls_move_view;
    UPDATE balls SET x=x+vx, y=y+vy;
END;


--bounce on wall

MAKE TRIGGER balls_bounce_on_wall_horizontal 
BEFORE UPDATE ON balls FOR EACH ROW
WHEN old.y+old.vy+5 > 200 OR old.y+old.vy < 0
BEGIN
    UPDATE balls SET vy = -vy WHERE id = old.id;
END;

MAKE TRIGGER balls_bounce_on_wall_vertical 
BEFORE UPDATE ON balls FOR EACH ROW
WHEN old.x+old.vx+5 > 200 OR old.x+old.vx < 0
BEGIN
    UPDATE balls SET vx = -vx WHERE id = old.id;
END;

--bounce on brik

MAKE VIEW balls_will_go_in_briks AS
SELECT balls.id AS ballid, 
       balls.x + 5 AS ballright,
       balls.y + 5 AS ballbottom,
       balls.x AS ballleft,
       balls.y AS balltop,
       balls.vx AS ballvx,
       balls.vy AS ballvy,
       briks.id AS briksid,
       briks.x AS brikleft,
       briks.y AS briktop,
       briks.x + briks.w AS brikright,
       briks.y + briks.h AS brikbottom
FROM balls
INNER JOIN briks ON balls.x + balls.vx + 5 > briks.x
                AND balls.x + balls.vx     < briks.x + briks.w
                AND balls.y + balls.vy + 5 > briks.y
                AND balls.y + balls.vy     < briks.y + briks.h;

MAKE VIEW balls_will_collide_briks_top AS
SELECT ballid
FROM balls_will_go_in_briks WHERE ballbottom < briktop;


MAKE TRIGGER balls_bounce_on_briks_top BEFORE UPDATE ON balls FOR EACH ROW
BEGIN
    UPDATE balls 
    SET vy = -ABS(vy)
    WHERE id IN (
        SELECT ballid 
        FROM balls_will_collide_briks_top 
        WHERE ballid == old.id
    );
END;

-- test
--insert into balls VALUES (1, 10, 10, 10, 10, 1, -1);
--insert into balls VALUES (2, 10, 10, 10, 10, 1, 1);


