require "app/bounce.rb"

BOUNCE_ACCL = 1.02
GRAVITY = 0.9
CX = 636
CY = 399
CR = 205

def tick args
  # INIT
  # circle
  cx = CX
  cy = CY
  cr = CR
  # pause
  args.state.paused = false if args.state.paused.nil?
  if args.state.ball.nil?
    args.state.ball = {
      x: 500,
      y: 500,
    }
    args.state.ball_vector = {
      x: 0,
      y: 0
    }
  end

  # INPUT
  if args.inputs.keyboard.key_up.space
    args.state.paused = !args.state.paused
  end

  # LOOP
  if !args.state.paused
    #ball vector
    move_x = args.state.ball_vector[:x]
    move_y = args.state.ball_vector[:y]
    # apply gravity
    move_y = move_y - GRAVITY
    args.state.ball_vector[:x] = move_x
    args.state.ball_vector[:y] = move_y

    # bounce
    x = args.state.ball[:x]
    y = args.state.ball[:y]
    new_x = x + move_x
    new_y = y + move_y
    if bouncing?(new_x,new_y,cx,cy,cr)
      new_move_x, new_move_y = reflection_vector(x,y,cx,cy,move_x,move_y)
      args.state.ball_vector[:x] = new_move_x * BOUNCE_ACCL
      args.state.ball_vector[:y] = new_move_y * BOUNCE_ACCL
    end

    # move the ball
    move_x = args.state.ball_vector[:x]
    move_y = args.state.ball_vector[:y]
    args.state.ball[:x] = args.state.ball[:x] + move_x
    args.state.ball[:y] = args.state.ball[:y] + move_y
  end

  # END?
  if !args.state.paused
    if too_fast?(move_x, move_y, cr)
      #RESET state and pause
      args.state.ball = {
        x: 500,
        y: 500,
      }
      args.state.ball_vector = {
        x: 0,
        y: 0
      }
      args.state.paused = true
    end
  end


  # RENDER
  #
  # BG
  args.outputs.sprites << {
    x: 0,
    y: 0,
    w: 1280,
    h: 720,
    path: 'sprites/BG1.png' }

  if  args.state.paused
    args.outputs.labels  << [640, 40, "Game is paused. Press <space> to continue", 4, 1]
  end

  # BALL
  args.outputs.sprites << {
    x: args.state.ball[:x]-16,
    y: args.state.ball[:y]-16,
    w: 32,
    h: 32,
    path: 'sprites/ball.png' }
end
