from flask import Flask, jsonify, render_template
import requests
import json

app = Flask(__name__)
# app.config['JSON_AS_ASCII'] = False


def getMask(): 
    page = 1
    datas = dict()
    while 1:
        response = requests.get('https://8oi9s0nnth.apigw.ntruss.com/corona19-masks/v1/stores/json?page=%d&perPage=500' % page)
        maskdict = json.loads(response.text)
        if len(maskdict.get('storeInfos')) == 0:
            break
        for b in maskdict.get('storeInfos'):
            datas[b.get('code')] = b;
        page = page + 1
    result = []
    page = 1
    while 1:
        print(page)
        response = requests.get('https://8oi9s0nnth.apigw.ntruss.com/corona19-masks/v1/sales/json?page=%d&perPage=500' % page)
        maskdict = json.loads(response.text)
        if len(maskdict.get('sales')) == 0:
            break
        for b in maskdict.get('sales'):
            y = b.get('code')
            if isinstance(y, dict):
               continue
            elif y in datas:
                data = datas[y]
                if data.get('lat'):
                    o = dict()
                    o['name'] = data.get('name')
                    o['addr'] = data.get('addr')
                    o['loc'] = [data.get('lat'), data.get('lng')]
                    o['remain_stat'] = b.get('remain_stat')
                    result.append(o)
        page = page + 1
    return result

@app.route("/")
def view():
    return render_template("final-corona.html", values=result)

if __name__ == "__main__":
    result = getMask()
    app.run(host="127.0.0.1", port="8080")