open System_defs
open Component_defs
open Ecs


let init dt =
  Ecs.System.init_all dt;
  Some ()


let update dt =
  let () = Player.stop_players () in
  let () = Input.handle_input () in
  Move_system.update dt;
  Collision_system.update dt;
  Draw_system.update dt;
  let s = (Global.get()).score in
  if s#score1#get > 5 then Some 1
  else if s#score1#get > 5 then Some 2
  else None

let prepare_message winner score _dt =
  let global = Global.get () in
  let font = Gfx.load_font Cst.font_name "" 64 in
  let text = Format.sprintf "Player %d wins" winner in
  Score.draw_text global.ctx font score text;
  global.waiting <- 3;
  Some ()

let wait dt =
  Draw_system.update dt;
  let () = Input.handle_input () in
  if (Global.get()).waiting <> 3 then Some () else None

let (let@) f k = f k

let run () =
  let window_spec = 
    Format.sprintf "game_canvas:%dx%d:"
      Cst.window_width Cst.window_height
  in
  let window = Gfx.create  window_spec in
  let ctx = Gfx.get_context window in
  let () = Gfx.set_context_logical_size ctx 800 600 in
  let font = Gfx.load_font Cst.font_name "" 128 in
  let rec loop () =
    let walls = Wall.walls () in
    let player1, player2 = Player.players () in
    let score = Score.score ctx font in
    let ball = Ball.ball ctx font in
    let global = Global.{ window; ctx; player1; player2; ball; waiting = 1; score; } in
    Global.set global;
    let@ () = Gfx.main_loop ~limit:false init in
    let@ winner = Gfx.main_loop update in
    List.iter Entity.delete walls;
    Entity.delete player1;
    Entity.delete player2;
    Entity.delete ball;
    let@ () = Gfx.main_loop (prepare_message winner score) in
    let@ () = Gfx.main_loop wait in
    Entity.delete score;
    loop ()
  in
  loop ()








