### Description: Displays the shoot all the hackers flickr album
### Category: Graphics
### License: GPL-3.0
### Appname: HackerGallery
### Built-in: no

# Navigation code taken from PhotoAlbum released MIT

import badge, easywifi, ugfx, gc, easydraw, woezel, ujson, random, machine

index = 0
num = 0
urls = []

def btn_b(pressed):
    if pressed:
        quit()

def display_flickr(photo):
    url = "https://f.0x52.eu/convert?url=https://farm{0}.staticflickr.com/{1}/{2}_{3}_m.jpg".format(photo["farm"], photo["server"], photo["id"], photo["secret"])
    data=requests.get(url)
    gc.collect()
    png_data = data.content
    data.close()
    gc.collect()
    width,height,bitdepth,colortype=badge.eink_png_info(png_data)
    gc.collect()
    badge.eink_png(0, 0, png_data)
    ugfx.flush()

easywifi.enable(True)
if easywifi.state==False:
    easydraw.msg("You need network for this app!","FAILURE")
    easydraw.msg("Waiting 5 seconds to try again!")
    badge.eink_busy_wait()
    machine.deepsleep(5000)

easydraw.msg("Checking for updates")
try:
    woezel.install('hacker_gallery')
    easydraw.msg("Updated! Rebooting now!")
    badge.eink_busy_wait()
    import machine
    machine.deepsleep(1)
except:
    ugfx.clear(ugfx.BLACK)
    ugfx.flush()
    ugfx.clear(ugfx.WHITE)
    ugfx.flush()
    ugfx.clear(ugfx.BLACK)
    ugfx.flush()
    ugfx.clear(ugfx.WHITE)
    ugfx.flush()

    ugfx.set_lut(ugfx.GREYSCALE)
    ugfx.init()
    ugfx.input_init()
    ugfx.input_attach(ugfx.JOY_LEFT,lambda pressed: btn_left(pressed))
    ugfx.input_attach(ugfx.JOY_RIGHT,lambda pressed: btn_right(pressed))

    ugfx.input_attach(ugfx.BTN_B,lambda pressed: btn_b(pressed))

    ugfx.orientation(90)
    easydraw.msg("Getting album information")

    import urequests as requests
    gc.collect()
    # please don't misuse this api_key
    album_wrapped=requests.get("https://api.flickr.com/services/rest/?format=json&method=flickr.photosets.getPhotos&api_key=2f67200e69bfdc97f4b290197f721d01&photoset_id=72157656607345496")
    gc.collect()
    # convert back to normal json
    album = ujson.loads(album_wrapped.text[14:][:-1])
    album_wrapped.close()
    while True:
        for photo in album["photoset"]["photo"]:
            display_flickr(photo)
            print(gc.mem_free())