#! /usr/bin/python3
from io import BytesIO
from numpy import asarray
from PIL import Image
from redis import Redis
import base64
import json
import os
import potrace
import re
import time

color = 65280
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
r         = Redis(host=host, port=port)


def convertImg(src, image_path="/tmp/"):
    base64_data = re.sub('^data:image/.+;base64,', '', src)
    byte_data = base64.b64decode(base64_data)
    image_data = BytesIO(byte_data)
    img = Image.open(image_data).convert("1")
    return img

# Read results from redis
data = r.lpop('image-convert')
while data :
  try:
    item = json.loads(data)
    image_data    = item["image_data"]
    text          = item["text"]
    hash_name     = item["hash_name"]

    # Vectorize the image
    image         = convertImg( image_data )
    bmp           = potrace.Bitmap( asarray( image ) )

    # Trace the bitmap to a path
    path          = bmp.trace(turdsize=16,alphamax=0.0, opticurve=0, opttolerance=1.0)
    pl            = []

    for curve in path:
      start     = curve.start_point
      pl.append([int(start[0]),int(start[1]),0])
      pl.append([int(start[0]),int(start[1]),color])
      for segment in curve:
        end_point_x, end_point_y = segment.end_point
        if segment.is_corner:
          c_x, c_y = segment.c
          pl.append([int(c_x),int(c_y),color])
          pass
        #
        else:
          c1_x, c1_y = segment.c1
          x, y = segment.c2
          pl.append([int(x),int(y),color])
          pl.append([int(c1_x),int(c1_y),color])
      #
      pl.append([start[0],start[1],0])
    item["points_list"] = pl
    item["created_at"]  = time.time()
    r.hset("images",hash_name, json.dumps(item))
    print("Handled image {}".format(hash_name))
    data = r.lpop('image-convert')

  except Exception as e:
    print("woops",e)
    break
