include, plotscr.hsd
include, scancode.hsi

global variable (1, tick)
global variable (2, button)
global variable (3, hold)
global variable (4, hold start tick)
global variable (5, hold caption)
define constant (18, second)

plotscript, main, begin
  suspend player
  load slice collection (1)
  set slice lookups (sprite layer)
  
  init mouse
  show mouse cursor
  button := lookup slice(999)
  if(running on console()) then(
    free slice(button)
    button := false
  )
  
  hold := 10
  hold caption := lookup slice(998)

  while (1) do, begin
    tick += 1
    update keyboard
    update click
    wait
  end
end

#Keyboard scancodes are stored in extra0, which we copy
#into the lookup for convenience (and for testing)
script, set slice lookups, sl, begin
  if (get slice extra (sl, 0)) then (
    set slice lookup (sl, get slice extra (sl, 0))
  )

  variable (child)
  child := first child (sl)
  while (child) do, begin
    set slice lookups (child)
    child := next sibling (child)
  end
end

script, update keyboard, begin
  variable (i, sl, st, gotkey)
  gotkey := false
  for (i, 0, 127) do, begin
    sl := lookup slice (i)
    if (sl == 0) then (continue)
    set rect style(sl, keyval(i) + 1)
    if(keyval(i) > 0) then(
      gotkey := true
    )
  end
  if(gotkey) then(
    if(hold start tick == 0) then(hold start tick := tick)
    if((tick -- hold start tick) > second) then(
      hold -= 1
      update hold caption
      if(hold == 0) then(
        if(keyval(key:K) > 0 || keyval(key:M) > 0) then(game over)
        try to email logs
        reset hold
      )else(
        hold start tick := tick
      )
    )
  )else(
    # no key being held
    reset hold
  )
end

script, reset hold, begin
  hold := 10
  hold start tick := 0
  update hold caption
end

script, update click, begin
  if(not(button)) then(exit script)
  if(mouse click(left button)) then(
    if(slice collide point(button, mouse pixel x, mouse pixel y)) then(
      try to email logs
    )
  )  
end

script, try to email logs, begin
  variable(box)
  box := create rect(320, 200)
  set rect fuzziness(box, 50)
  show text box(1)
  wait(8)
  save in slot(1)
  send email(1, $1="OHRRPGCE input test feedback", $2="This e-mail contains debugging logs for the OHRRPGCE input testing App. It does not contain personal data of any kind. You can add your comments to this e-mail before sending.")
  wait(7)
  advance text box
  wait(1)
  free slice(box)
end

script, update hold caption, begin
  set slice text(hold caption, string sprintf(0, $1="E-mail log file by holding a button for %d seconds. Hold BACK or MENU to quit.", hold))
end



