
local csm = require('csm')
local core = require('core')
local graphics = require('graphics')
local draw = require('draw')
local Image = require('image')
local clock = require('clock')
local timer = require('timer')

local mygui
local mycsm
local my_timer
local w = graphics.width()-1
local h = graphics.height()-1
local y = 0
local x = 0
local suy = 4
local sux = 4
local no_draw = false
local fps = 0
local fps_count = 0
local cur_time = 0
local dtext

local img = Image()
img:loadFromPng(sys.pDir().."default.png")

local i_h = img:height()
local i_w = img:width()

local black = draw.getColor(0, 0, 0, 0x64)
local red = draw.getColor(255, 0, 0, 0x64)
local green = draw.getColor(0, 255, 0, 0x64)


--collectgarbage('setpause', 1000)


-- ============== gui ===============

function onRedraw()
  if no_draw then return end

  draw.drawRoundedFrame(0, 0, w, h, 0, 0, 0, black, black)
  
  dtext = fps.." fps"
  draw.drawScrollString(dtext, #dtext, 0, 0, w, h, 1, 11, 32, green, red)
  
  img:draw(x, y)
  
  y = y+suy
  x = x+sux
  
  
  if(x+i_w > w) then
    sux = -4
  elseif x < 0 then
    sux  = 4
  end
  
  
  if(y+i_h > h) then
    suy = -4
  elseif y < 0 then
    suy  = 4
  end
  
  
  if cur_time ~= (clock.time().sec)  then
    fps = fps_count
    fps_count = 0
    cur_time = clock.time().sec
  end
  
  fps_count = fps_count+1
  my_timer = nil
  my_timer = timer.start(onRedraw, 1 )
end



local function drawing()
  if no_draw == false then
    return
  end
end



local function onCreate()

end


local function onClose()
  img:release()
end


local function onFocus()
  no_draw = false
  print('onFocus')
end


local function onUnFocus()
  no_draw = true
  if my_timer ~= nil then
    my_timer:stop()
  end
  print('onUnFocus')
end


local function onKey(type, key)
  
  if key == 4 then
    no_draw  = false
    if my_timer ~= nil then
      my_timer:stop()
    end
    print('! Close !')
    return 1
  end

  --gui.redraw()
  return 0
end


-- ============== csm ===============

local  function csm_onCreate(csm_data)
  
   mygui = graphics.new(onRedraw,
       onCreate,
       onClose,
       onFocus, 
       onUnFocus,
       onKey)

  csm.parentOfGui(csm_data, mygui:id());
end


function onExit(csm_data)
  mygui = nil
  mycsm = nil
  sys.exit();
end


function onMessage(csm_data, msg)
  return 1
end


mycsm = csm.new(1, "Lua crazy", csm_onCreate, onExit, onMessage)



