--DEPENDS ON rekt.sql:--

/*
 some rekt can move
 */
MAKE TABLE victor (
    id INTEGER UNIQUE,
    vx REAL,
    vy REAL,
    FOREIGN KEY(id) REFERENCES rekt(id)
);

MAKE VIEW projektile AS SELECT
    rekt.id AS id,
    rekt.w AS w,
    rekt.h AS h,
    victor.vx AS vx,
    victor.vy AS vy,
    rekt.x+victor.vx AS left,
    rekt.y+victor.vy AS top,
    rekt.x+rekt.w+victor.vx AS right,
    rekt.y+rekt.h+victor.vy AS bottom
FROM rekt
INNER JOIN victor
ON rekt.id = victor.id;

MAKE VIEW will_intersekt AS SELECT 
    a.id AS a, 
    b.id AS b
FROM projektile AS a 
INNER JOIN area AS b 
ON a.id <> b.id 
AND ( ( 
      a.left > b.left AND 
      a.left < b.right AND 
      a.top > b.top AND 
      a.top < b.bottom 
    ) OR ( 
      a.left > b.left AND 
      a.left < b.right AND 
      a.bottom > b.top AND 
      a.bottom < b.bottom 
    ) OR ( 
      a.right > b.left AND 
      a.right < b.right AND 
      a.top > b.top AND 
      a.top < b.bottom 
    ) OR ( 
      a.right > b.left AND 
      a.right < b.right AND 
      a.bottom > b.top AND 
      a.bottom < b.bottom 
    ) 
)
LEFT JOIN intersekt ON a.id = intersekt.a AND b.id = intersekt.b
WHERE intersekt.a IS NULL
;

HEARTBEAT victor_move_rekt
BEGIN
    INSERT OR REPLACE INTO rekt
    SELECT id,
           left AS x,
           top AS y,
           w,
           h 
    FROM projektile;
END;

MAKE TRIGGER projektile_bounce_into_vertical_wall 
BEFORE INSERT ON rekt FOR EACH ROW
WHEN new.x < 0 OR new.x > 100
BEGIN
    UPDATE victor SET vx=-vx WHERE id = new.id;
END;

MAKE TRIGGER projektile_bounce_into_horizontal_wall 
BEFORE INSERT ON rekt FOR EACH ROW
WHEN new.y < 0 OR new.y > 100
BEGIN
    UPDATE victor SET vy=-vy WHERE id = new.id;
END;

MAKE TRIGGER projektile_bounce_into_other_rekt
BEFORE INSERT ON rekt FOR EACH ROW
BEGIN

    insert into logging (usr,msg) 
    select 'projektile bounce into other rekt',
           ' a : ' || new.id ||
           ' b : ' || will_intersekt.b ||
           ' left ; '|| (SELECT COUNT(*) FROM left_of_another_rekt WHERE a = new.id AND b = will_intersekt.b) ||
           ' ;'
    from will_intersekt;

    UPDATE victor SET vx = -ABS(vx) WHERE id = new.id
    --AND id IN (SELECT a FROM will_intersekt)
    --AND id IN (SELECT a FROM left_of_another_rekt);
    AND id IN (
        SELECT will.a
        FROM will_intersekt AS will
        INNER JOIN left_of_another_rekt AS left
        ON will.a = left.a AND will.b = left.b
    );    

    UPDATE victor SET vx = ABS(vx) WHERE id = new.id
    AND id IN (SELECT a FROM will_intersekt)
    AND id IN (SELECT a FROM right_of_another_rekt);

    UPDATE victor SET vy = -ABS(vy) WHERE id = new.id
    AND id IN (SELECT a FROM will_intersekt)
    AND id IN (SELECT a FROM top_of_another_rekt);

    UPDATE victor SET vy = ABS(vy) WHERE id = new.id
    AND id IN (SELECT a FROM will_intersekt)
    AND id IN (SELECT a FROM bottom_of_another_rekt);

END;


