var render = use('render')
var os = use('os')
var actor = use('actor')
var transform = use('transform')
var dim = [500,500]
render.initialize({
  width:dim.x,
  height:dim.y,
  resolution_x:dim.x,
  resolution_y:dim.y,
  mode:"letterboxed",
  refresh: 60,
})

var camera = {
  size: [500,500],
  transform: new transform,
  fov:50,
  near_z: 0,
  far_z: 1000,
  surface: null,
  viewport: {x:0,y:0,width:1,height:1},
  ortho:true,
  anchor:[0,0],
}

var draw = use('draw2d')
var sprite = use('lcdsprite')
var graphics = use('graphics')

var dt = 0
var img = "alcinaqr"

var ioguy = {
  __ACTORDATA__: { id: actor.ioactor() }
}

var io = use('io')
io.mount('/')
var miniz = use('miniz')

var nota = use('nota')

var qr = use('qr')

var lvl = io.slurp('tests/level.json')
var lvl_json = lvl
log.console(`json size is ${lvl.length}`)
lvl = json.decode(lvl)
lvl = nota.encode(lvl)
log.console(`nota size is ${lvl.byteLength}`)
var lvl_cmp = miniz.compress(lvl)
var lvl_json_cmp = miniz.compress(lvl_json)

log.console(`compressed json is ${lvl_json_cmp.byteLength}`)
log.console(`compressed nota is ${lvl_cmp.byteLength}`)

var uncmp = miniz.decompress(lvl_cmp, false)
log.console(uncmp.byteLength)

log.console(`json cmp width: ${qr.encode(lvl_json_cmp).width}`)
var qr_lvl = qr.encode(lvl_cmp)
log.console(`nota cmp width: ${qr_lvl.width}`)
var lvl_bytes = qr.rgba(qr_lvl)

log.console(lvl_bytes.buffer.byteLength)
log.console(json.encode(lvl_bytes))

var bsurf = graphics.surface_from_pixels(lvl_bytes)

var frame_img = graphics.texture("alcinaqr")

var blit_img = graphics.from_surface("frame", frame_img.cpu.dup())

var qr_size = lvl_bytes.width*4
log.console(`blowing it up to ${qr_size}`)
var qr_rect = {x:300, y:500, width:qr_size, height:qr_size}
var gutter = 25 // pixels per side
var qr_rect_gutter = {
  x: qr_rect.x - gutter,
  y: qr_rect.y - gutter,
  width: qr_rect.width + gutter*2,
  height: qr_rect.height + gutter*2
}
blit_img.cpu.blit(qr_rect, bsurf, null, "nearest")

graphics.save_png("blit.png", blit_img.cpu.width, blit_img.cpu.height, blit_img.cpu.pixels(), blit_img.cpu.pitch)

graphics.save_jpg("blit.png", blit_img.cpu.width, blit_img.cpu.height, blit_img.cpu.pixels(), 1)

graphics.save_png("qrblit.png", bsurf.width, bsurf.height, bsurf.pixels(), bsurf.pitch)

var qr_img = graphics.from_surface("qr", bsurf)

img = frame_img

send(ioguy, {
  type: "subscribe",
  actor: $_
})

function strToArrayBuffer(binStr) {
  def view = new Uint8Array(binStr.length);
  for (let i = 0; i < binStr.length; i++)
    view[i] = binStr.codePointAt(i) & 0xff;   // mask keeps it 0-255
  return view.buffer;
}

var http = use('http')

function is_url(str)
{
  return /^https?:\/\/[^\s/$.?#].[^\s]*$/i.test(str)
}

function parse_data(res)
{
  if (!res.type.startsWith('image')) return
  img = graphics.texture_from_data(res.data)
}

function extract_qr_surface(surface)
{
  var qr = graphics.make_surface([qr_rect_gutter.width, qr_rect_gutter.height])
  qr.blit(null, surface, qr_rect_gutter)
  return qr
}

var display = null

$_.receiver(e => {
  if (e.type == 'quit')
    os.exit()

  switch(e.type) {
    case "drop_file":
      log.console(`got ${e.data} dropped`)
      var data = io.slurpbytes(e.data)
      img = graphics.make_texture(data)
      var qr_surf = img;//extract_qr_surface(img)
      var qr_surf_scaled = qr_surf.scale([qr_surf.width/4, qr_surf.height/4])
      var image = {surface:qr_surf_scaled}
      display = graphics.from_surface("aaa", qr_surf_scaled)
      var data = qr.decode(image.surface.pixels(), image.surface.width, image.surface.height, image.surface.pitch)
      log.console(`found ${data.length} qr codes`)
      if (data.length == 0) break
      data = data[0]
      log.console(data.byteLength)
      var ddata = miniz.decompress(data, false)
      log.console(ddata.byteLength)
      log.console(`qr data size was ${data.byteLength}, uncompressed ${ddata.byteLength}`)
      
      var nn = nota.decode(ddata)
      log.console(json.encode(nn))
      break;
      
    case "drop_text":
      log.console(`text ${e.data} dropped`)    
      // if e.data is a url, fetch it
      if (is_url(e.data)) {
        log.console('fetching!')
        http.fetch(e.data, parse_data)
      }
      break;
  }
})

function loop()
{
  http.poll();
  var now = os.now()
  render.clear([22/255,120/255,194/255,255/255])
  render.camera(camera)
  
  draw.image(frame_img, {x:20,y:100, width:200,height:300})
  draw.image(qr_img, {x:400, y:100})
  draw.image(blit_img, {x:250, y:0, width:100, height: 150})
  if (display)
    draw.image(display, {x:0,y:0,width:200,height:200})
  
//  if (img)
//    draw.image(img, {x:0,y:0,width:300,height:300})

  render.present()

  dt = os.now() - now
  var delay = (1/60) - dt
  $_.delay(loop, delay)
}

loop()
