import redis
from time import sleep
import random
from io import BytesIO
import numpy as np
from PIL import Image
import matplotlib.pyplot as plt

import ast

redis_ip = "192.168.159.39"

print("*********************")
print("Test Python data exchange with Java via redis.")
print("")
r = redis.Redis(host=redis_ip, port=6379, db=0)

print("Redis connection: ", redis_ip)


def show_image(image_raw_bytes):
    raw_io = BytesIO(image_raw_bytes)
    img = Image.open(raw_io)
    x = np.array(img)
    plt.imshow(x)
    plt.show()


last_count = 0

while True:
    loop_get_counter = True
    iteration = 1

    print("Waiting for redis java key: \"counter\"...")
    while loop_get_counter:
        counter = r.get("counter")
        iteration += 1
        print("Get redis \"counter\": ", counter)
        try:
            if last_count == 0:
                print("First time program run.")
                last_count = counter
                loop_get_counter = False

            if ast.literal_eval(counter.decode("utf-8")) > ast.literal_eval(last_count.decode("utf-8")):
                last_count = counter
                loop_get_counter = False

        except AttributeError as error:
            print("%d No value for counter" % iteration)

        sleep(0.5)

    img_counter = "img:" + counter.decode("utf-8")
    infer_counter = "infer:" + counter.decode("utf-8")
    print("Get java key: ", img_counter)

    image = r.get(img_counter.encode())
    print("Get image for java key: ", img_counter)
    show_image(image)

    # add infer code here, to mimic code, send back a random binary value, 0 or 1
    infer_intruder = random.randint(0, 1)
    print("infer_intruder: ", infer_intruder)
    infer_intruder = str(infer_intruder)
    counter_decode = counter.decode("utf-8")
    if infer_intruder == '0':
        print("Counter %s:  0" % counter_decode)
    else:
        print("Counter %s:  1" % counter_decode)

    # delete image from db
    r.unlink(img_counter)
    print("Deleted redis java key: ", img_counter)

    r.set("infer:" + counter.decode("utf-8"), infer_intruder)
    print("Set %s for redis python key: \"infer:%s\"" % (infer_intruder,  counter_decode))
