#! /usr/bin/python3
from redis import Redis
from flask import Flask, redirect, url_for, request
import flask
import hashlib
import json
import os
import time
import sys

# Redis init
environ = os.environ
host = environ['DB_HOST'] if 'DB_HOST' in os.environ else "localhost"
port = environ['DB_PORT'] if 'DB_PORT' in os.environ else 6379
debug = environ['DEBUG'] if 'DEBUG' in os.environ else False
sep='**************************************'
print("\n{}\nConnecting to Redis server on {}:{}\n{}\n".format(sep,host,port,sep))
r         = Redis(host=host, port=port)

# hashlib init
m = hashlib.sha256()

# Flask app init
app = Flask(__name__)

@app.before_first_request
def setup_logging():
    if not app.debug:
        # In production mode, add log handler to sys.stdout.
        app.logger.addHandler(logging.StreamHandler(stream=sys.stdout))
        app.logger.setLevel(logging.INFO)

# Routing requests
@app.route('/image',methods = ['POST', 'GET'])
def image():
  try:
    data = dict()

    res =r.keys("*")
    # Clean the request
    if "text" in request.form:
      data["text"] = request.form["text"][:256]
    else :
      data["text"] = ""

    if "image_data" in request.form:
      data["image_data"] = request.form["image_data"]
    else:
      raise Exception("image_data is mandatory")

    m.update( bytes(time.asctime(), 'utf-8'))
    hash_name = m.hexdigest()[:16]
    data["hash_name"] = hash_name

    # Save to queue
    r.rpush("image-convert",json.dumps(data))
    return( json.dumps({
      "message":"ok",
      "hash_name":hash_name
    }) )

  except Exception as e:
    print("woah",e)
    return( json.dumps( {"errors":[ str(e)]}))

@app.route('/hash_name/<hash_name>',methods = ['GET'])
def hash_name(hash_name):
  try:

    item = json.loads(r.hget("images",hash_name))
    if not item:
      raise Exception("This image is not available now. You might need to wait a bit more?")
    return( json.dumps({
      "message":"ok",
      "points_list":item["points_list"]
    }) )

  except Exception as e:
    print("woah",e)
    return( json.dumps( {"errors":[ str(e)]}))

# Run Flask
if __name__ == '__main__':
   app.run(host= '0.0.0.0',debug = True)
