import badge, ugfx

global x, y

width = 4350
height = 3600

x = int((width - 296) / 2)
y = int((height - 128) / 2)

badge.init()
ugfx.init()

def download_tile(px,py):
  import easywifi
  easywifi.enable(False)
  import woezel
  import uos
  try:
    uos.mkdir('/data')
  except:
    pass
  try:
    uos.mkdir('/data/maps')
  except:
    pass
  url = 'https://badge.sha2017.org/data/maps/tile_%02d_%02d.png' % (px, py)
  file = '/data/maps/tile_%02d_%02d.png' % (px, py)
  s = woezel.url_open(url)
  with open(file, 'wb') as f:
    buf = s.read(1024)
    while len(buf) > 0:
      f.write(buf)
      buf = s.read(1024)
  s.close()

def display():
  missing_tiles = []
  for px in range(0, 29):
    pxpos = px * 150
    if pxpos + 150 > x and x + 296 > pxpos:
      for py in range(0, 24):
        pypos = py * 150
        if pypos + 150 > y and y + 128  > pypos:
          try:
            file = '/data/maps/tile_%02d_%02d.png' % ( px, py )
            badge.eink_png(pxpos-x, pypos-y, file)
          except:
            missing_tiles += [(px, py)]
            badge.eink_png(pxpos-x, pypos-y, '/lib/maps/missing.png')
  ugfx.flush(ugfx.GREYSCALE)
  if len(missing_tiles) > 0:
    for tile in missing_tiles:
      download_tile(tile[0], tile[1])
    for px in range(0, 29):
      pxpos = px * 150
      if pxpos + 150 > x and x + 296 > pxpos:
        for py in range(0, 24):
          pypos = py * 150
          if pypos + 150 > y and y + 128  > pypos:
            try:
              file = '/data/maps/tile_%02d_%02d.png' % ( px, py )
              badge.eink_png(pxpos-x, pypos-y, file)
            except:
              missing_tiles += (px, py)
              badge.eink_png(pxpos-x, pypos-y, '/lib/maps/missing.png')
    ugfx.flush(ugfx.GREYSCALE)

def do_left(pressed):
  global x
  if pressed and x > 0:
    x -= 222
    if x < 0:
      x = 0
    display()

def do_right(pressed):
  global x
  if pressed and x < width - 296:
    x += 222
    if x > width - 296:
      x = width - 296
    display()

def do_up(pressed):
  global y
  if pressed and y > 0:
    y -= 96
    if y < 0:
      y = 0
    display()

def do_down(pressed):
  global y
  if pressed and y < height - 128:
    y += 96
    if y > height - 128:
      y = height - 128
    display()

def do_b(pressed):
  if pressed:
    import appglue
    appglue.home()

ugfx.input_init()
ugfx.input_attach(ugfx.JOY_LEFT, do_left)
ugfx.input_attach(ugfx.JOY_RIGHT, do_right)
ugfx.input_attach(ugfx.JOY_UP, do_up)
ugfx.input_attach(ugfx.JOY_DOWN, do_down)
ugfx.input_attach(ugfx.BTN_B, do_b)

display()