#!/usr/bin/env python3
import os
import json
import argparse
import subprocess
import tempfile
import base64
from flask import Flask, request, Response
app = Flask(__name__)

@app.route('/', methods=['GET'])
@app.route('/alg', methods=['GET'])
def index():
    return make_resp({})

def oss_save_image(data_url, file_prefix):
    ak = 'LTAI5tC2qXGxwHZUZP7DoD1A'
    sk = 'qPo9O6ZvEfqo4t8oflGEm0DoxLHJhm'
    auth = oss2.Auth(ak, sk)
    endpoint = 'oss-cn-guangzhou.aliyuncs.com'
    bucket_name = 'emblem-roi-samples'
    bucket = oss2.Bucket(auth, endpoint, bucket_name)

    pref = 'data:image/png;base64,'
    if data_url.startswith(pref):
        decoded = base64.b64decode(data_url[len(pref):])
        fname = file_prefix + str(time.time()) + ".png"
        bucket.put_object(fname, decoded)


def make_resp(content):
    resp = Response(json.dumps(content))
    resp.headers['Access-Control-Allow-Origin'] = "*"
    resp.headers['Access-Control-Allow-Methods'] = '*'
    resp.headers['Access-Control-Allow-Headers'] = '*'
    resp.headers['Content-Type'] = 'application/json'
    return resp

@app.route('/alg/angle', methods=['POST', 'OPTIONS'])
def angle():
    try:
        return handle_angle_request()
    except Exception as e:
        return make_resp({
            "ok": False,
            "err": str(e),
            })

def handle_angle_request():
    if request.method == 'OPTIONS':
        return make_resp({})
    body = request.stream.read()
    pref = 'data:image/jpeg;base64,'
    err = "Cannot detect angle"
    angle = -1
    try:
        encoded = body.decode()
        if encoded.startswith(pref):
            decoded = base64.b64decode(encoded[len(pref):])
        else:
            decoded = body
    except:
        decoded = body
    with tempfile.NamedTemporaryFile(dir="uploads", suffix=".jpg", delete=False) as tf:
        tf.write(decoded)
        tf.flush()
        cmd = ['./qrtool', 'angle', tf.name]
        print(" ".join(cmd))
        r = subprocess.run(cmd, capture_output=True)
        if r.returncode == 0:
            lines = r.stdout.decode().splitlines()
            return make_resp({
                "ok": True,
                "qrcode": lines[0].split()[1],
                "angle": int(lines[1].split()[1])
            })
        else:
            err = r.stderr.decode()
    return make_resp({
        "ok": False,
        "err": err,
    })

def handle_rectify_request():
    body = request.stream.read()
    with tempfile.NamedTemporaryFile() as tf:
        tf.write(body)
        tf.flush()
        outf = tf.name + ".qr.jpg"
        cmd = ['./qrtool', 'rectify', tf.name]
        subprocess.check_call(cmd)
        with open(outf, 'rb') as of:
            resp = Response(of.read(), status=200, mimetype='image/jpeg')
    os.unlink(outf)
    return resp

@app.route('/alg/rectify', methods=['POST', 'OPTIONS'])
def rectify():
    try:
        return handle_rectify_request()
    except Exception as e:
        return make_resp({
            "ok": False,
            "err": str(e),
            })

def parse_args():
    parser = argparse.ArgumentParser()
    parser.add_argument("--host", "-l", default="0.0.0.0")
    parser.add_argument("--port", "-p", type=int, default=3028)
    return parser.parse_args()

if __name__ == '__main__':
    args = parse_args()
    app.run(host=args.host, port=args.port)
