import cv2
import numpy as np
from rdp import rdp

def edges(gray_image):
    threshold_1 = 0
    threshold_diff = 40
    threshold_2 = threshold_1 + threshold_diff
    edges_image = cv2.Canny(gray_image, threshold_1, threshold_2)
    contours, _ = cv2.findContours(edges_image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    new_contours = []

    # here we create the contours in XYZ

    for i in range(len(contours)):
        if (len(contours[i]) >= 10):
            new_contours.append([contours[i][0][0][0], contours[i][0][0][1], 25])  # create a point at Z = 25 before
            for j in range(len(contours[i])):
                x = contours[i][j][0][0]
                y = contours[i][j][0][1]
                z = 0
                new_contours.append([x, y, z])
            new_contours.append([contours[i][len(contours[i]) - 1][0][0], contours[i][len(contours[i]) - 1][0][1], 25])
    iteration = 0

    while len(new_contours) >= 6000:
        threshold_1 = 40 + iteration*20
        threshold_2 = threshold_1 + threshold_diff
        edges_image = cv2.Canny(gray_image, threshold_1, threshold_2)
        contours, _ = cv2.findContours(edges_image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
        new_contours = []

        for i in range(len(contours)):
            if (len(contours[i]) >= 10):
                new_contours.append([contours[i][0][0][0], contours[i][0][0][1], 25])  # create a point at Z = 25 before
                for j in range(len(contours[i])):
                    x = contours[i][j][0][0]
                    y = contours[i][j][0][1]
                    z = 0
                    new_contours.append([x, y, z])
                new_contours.append([contours[i][len(contours[i]) - 1][0][0], contours[i][len(contours[i]) - 1][0][1], 25])

        name = "points : " + str(len(new_contours)) + ", th1 : " + str(threshold_1) + ", th2 : " + str(threshold_2)
        #print(name, iteration)

        iteration += 1
        #cv2.imshow(name, edges_image)

    #cv2.waitKey(0)
    coords = simplified_coords(contours)
    print("nb points before optimisation : ", len(new_contours))
    print("optimisation rate : ", round((len(new_contours) - len(coords))/len(new_contours), 2))
    return coords

def simplified_coords(contours):
    old_points = []
    coords = []

    for i in range(len(contours)):
        for j in range(len(contours[i])):
            x = contours[i][j][0][0]
            y = contours[i][j][0][1]
            if (j+1 == len(contours[i])) or j == 0:
                z = 15
            else:
                z = 0
            old_points.append([x, y, z])
        new_points = rdp(old_points, 1.0)
        #print(new_points)
        #print(len(new_points)/len(old_points))
        for k in new_points:
            coords.append(k)
        old_points = []
    print("nb points after optimisation : ", len(coords))
    return coords
