A slate to write and draw on, then export to html
run = {}

Editor_state = {}

-- called both in tests and real run
function run.initialize_globals()
  -- tests currently mostly clear their own state

  Font_height = 20
  Line_height = math.floor(Font_height*1.3)
  Menu_bar_height = Menu_top + 5 + Line_height + 5

  -- state machine:
  --  states:
  --    - editing: if Export_filename_value == nil
  --    - export: if Export_filename_value and not Export_filename_doublecheck
  --    - doublecheck: if Export_filename_doublecheck
  --  the way these are defined, Export_filename_doublecheck has higher priority in branches than Export_filename_value
  --  transitions:
  --    editing | press 'export' button -> export
  --    export | hit return ->
  --      | Export_filename_value doesn't exist -> editing [after writing]
  --      | Export_filename_value exists -> doublecheck
  --    doublecheck | hit return -> editing [after writing]
  --    doublecheck | hit some other key -> editing [cancel]
  Export_filename_value = nil
  Export_filename_doublecheck = false
    Export_filename_doublecheck_pressed = false  -- substate I wish we didn't need

  Current_flash = nil
  Current_flash_time = nil

  -- blinking cursor
  Cursor_time = 0
end

-- called only for real run
function run.initialize(arg)
  log_new('run')
  -- maximizing on iOS breaks text rendering: https://github.com/deltadaedalus/vudu/issues/7
  -- no point second-guessing window dimensions on mobile
  App.screen.width, App.screen.height, App.screen.flags = App.screen.size()
  if Settings then
    run.load_settings()
  else
    run.initialize_default_settings()
  end

  if #arg > 0 and Editor_state.filename ~= absolutize(arg[1]) then
    Editor_state.filename = arg[1]
    load_from_disk(Editor_state)
    Text.redraw_all(Editor_state)
    Editor_state.screen_top1 = {line=1, pos=1}
    Editor_state.cursor1 = {line=1, pos=1}
  else
    load_from_disk(Editor_state)
    Text.redraw_all(Editor_state)
  end
  edit.check_locs(Editor_state)



  -- keep a few blank lines around: https://merveilles.town/@akkartik/110084833821965708
  love.window.setTitle('etch.love - '..Editor_state.filename)



  if #arg > 1 then
    print('ignoring commandline args after '..arg[1])
  end

  if rawget(_G, 'jit') then
    jit.off()
    jit.flush()
  end
end

function print_and_log(s)
  print(s)
  log(3, s)
end

function run.load_settings()
  Font_height = Settings.font_height
  Line_height = math.floor(Font_height*1.3)
  local font = love.graphics.newFont(Font_height)
  Editor_state = edit.initialize_state(Menu_bar_height + Margin_top, Margin_left, App.screen.width-Margin_right, font, Font_height, Line_height)
  Editor_state.filename = Settings.filename
  Editor_state.screen_top1 = Settings.screen_top
  Editor_state.cursor1 = Settings.cursor
end

function run.initialize_default_settings()
  Font_height = 20
  Line_height = math.floor(Font_height*1.3)
  Menu_bar_height = 5 + Line_height + 5
  local font = love.graphics.newFont(Font_height)
  Editor_state = edit.initialize_state(Menu_bar_height + Margin_top, Margin_left, App.screen.width-Margin_right, font, Font_height, Line_height)
  Settings = run.settings()
end

function run.draw()
  Editor_state.button_handlers = {}
  if App.run_tests == nil then
    if not Export_filename_value then
      -- case 1
      run.draw_buttons()
    elseif Export_filename_doublecheck then
      -- case 2
      love.graphics.setColor(0,1,0)
      love.graphics.print(Export_filename_value..' already exists. Overwrite? Hit enter/return to confirm, any other key to cancel', 15, 5)
    end
  end
  edit.draw(Editor_state)
  if Export_filename_value and not Export_filename_doublecheck then
    -- case 3
    run.draw_export_filename_bar()
  end
end

function run.draw_buttons()
  local button_text = 'clear'
  local width = Editor_state.font:getWidth(button_text)
  local x=Menu_left+5
  button(Editor_state, button_text, {x=x, y=Menu_top, w=width+10,h=Line_height, bg={r=1,g=0.7,b=1},
      icon = function(button_params)
        local x,y = button_params.x, button_params.y
        local w,h = button_params.w, button_params.h
        love.graphics.setColor(0.4,0.4,0.7)
        love.graphics.rectangle('line', x,y, w,h, 5,5)
        love.graphics.setColor(0,0,0)
        love.graphics.print(button_text, x+5, y)
      end,
      onpress1 = function()
        Editor_state.lines = {{mode='text', data=''}}
        Text.redraw_all(Editor_state)
        Editor_state.screen_top1 = {line=1, pos=1}
        Editor_state.cursor1 = {line=1, pos=1}
        schedule_save(Editor_state)
      end,
  })
  x = x+width+10 + 10
  button_text = 'export'
  width = Editor_state.font:getWidth(button_text)
  button(Editor_state, button_text, {x=x, y=Menu_top, w=width+10,h=Line_height, bg={r=1,g=0.7,b=1},
      icon = function(button_params)
        local x,y = button_params.x, button_params.y
        local w,h = button_params.w, button_params.h
        love.graphics.setColor(0.4,0.4,0.7)
        love.graphics.rectangle('line', x,y, w,h, 5,5)
        love.graphics.setColor(0,0,0)
        love.graphics.print(button_text, x+5, y)
      end,
      onpress1 = function()
        Export_filename_value = ''
      end,
  })
  x = x+width+10 + 10
  if Current_flash then
    App.color{r=0,g=0.4,b=0}
    love.graphics.print(Current_flash, x, Menu_top)
  end
end

function run.draw_export_filename_bar()
  local h = Line_height+2
  local y = Menu_top+10
  love.graphics.setColor(0.9,0.9,0.9)
  love.graphics.rectangle('fill', Menu_left, y-10, App.screen.width-1, h+8)
  love.graphics.setColor(0.6,0.6,0.6)
  love.graphics.line(Menu_left, y-10, App.screen.width-1, y-10)
  App.color(Text_color)
  local prompt = 'file name to save to: '
  love.graphics.print(prompt, 15, y-5)
  love.graphics.setColor(1,1,1)
  local text_start_x = Menu_left + Editor_state.font:getWidth(prompt)+20
  love.graphics.rectangle('fill', text_start_x-5, y-6, App.screen.width-text_start_x-20, h+2, 2,2)
  love.graphics.setColor(0.6,0.6,0.6)
  love.graphics.rectangle('line', text_start_x-5, y-6, App.screen.width-text_start_x-20, h+2, 2,2)
  App.color(Text_color)
  App.screen.print(Export_filename_value, text_start_x,y-5)
  Text.draw_cursor(Editor_state, text_start_x+Editor_state.font:getWidth(Export_filename_value),y-5)
end

function run.update(dt)
  Cursor_time = Cursor_time + dt
  edit.update(Editor_state, dt)
  if Current_flash then
    if App.get_time() - Current_flash_time > 3 then
      Current_flash = nil
      Current_flash_time = nil
    end
  end
end

function run.quit()
  edit.quit(Editor_state)
end

function run.settings()
  if Settings == nil then Settings = {} end
  Settings.x, Settings.y, Settings.displayindex = App.screen.position()
  return {
    font_height=Editor_state.font_height,
    filename=absolutize(Editor_state.filename),
    screen_top=Editor_state.screen_top1, cursor=Editor_state.cursor1
  }
end

function absolutize(path)
  if is_relative_path(path) then
    return App.current_dir..path
  end
  return path
end

function run.mouse_press(x,y, mouse_button)
  Cursor_time = 0  -- ensure cursor is visible immediately after it moves
  if Export_filename_value then return end
  love.keyboard.setTextInput(true)  -- bring up keyboard on touch screen
  edit.mouse_press(Editor_state, x,y, mouse_button)
end

function run.mouse_release(x,y, mouse_button)
  Cursor_time = 0  -- ensure cursor is visible immediately after it moves
  if Export_filename_value then return end
  edit.mouse_release(Editor_state, x,y, mouse_button)
end

function run.keychord_press(chord, key)
  Cursor_time = 0  -- ensure cursor is visible immediately after it moves
  if Export_filename_doublecheck then
    if chord == 'return' then
      local outfilename = love.filesystem.getSourceBaseDirectory()..'/'..Export_filename_value..'.html'
      export(outfilename)
      Current_flash = 'exported'
      Current_flash_time = App.get_time()
    end
  elseif Export_filename_value then
    if chord == 'escape' then
      Export_filename_value = nil
    elseif chord == 'return' then
      local outfilename = love.filesystem.getSourceBaseDirectory()..'/'..Export_filename_value..'.html'
      if file_exists(outfilename) then
        Export_filename_doublecheck_pressed = true
      else
        export(outfilename)
        Export_filename_value = nil
        Current_flash = 'exported'
        Current_flash_time = App.get_time()
      end
    elseif chord == 'backspace' then
      local len = utf8.len(Export_filename_value)
      local byte_offset = Text.offset(Export_filename_value, len)
      Export_filename_value = string.sub(Export_filename_value, 1, byte_offset-1)
    end
  else
    edit.keychord_press(Editor_state, chord, key)
  end
end

function run.text_input(t)
  Cursor_time = 0  -- ensure cursor is visible immediately after it moves
  if Export_filename_doublecheck then
    -- nothing
  elseif Export_filename_value then
    Export_filename_value = Export_filename_value..t
    return
  else
    edit.text_input(Editor_state, t)
  end
end

function run.key_release(key, scancode)
  Cursor_time = 0  -- ensure cursor is visible immediately after it moves
  if Export_filename_doublecheck_pressed then
    Export_filename_doublecheck = true
    Export_filename_doublecheck_pressed = false
  elseif Export_filename_doublecheck then
    -- clean up after text_input is done using Export_filename_doublecheck
    Export_filename_value = nil
    Export_filename_doublecheck = false
  elseif Export_filename_value then
    -- nothing
  else
    edit.key_release(Editor_state, key, scancode)
  end
end

function width(s)
  return love.graphics.getFont():getWidth(s)
end