import os
import cv2
import numpy as np
import matplotlib.pyplot as plt
from qrdecode.main import Scanner, QRProcessor
from qrdecode.utils.image import ImageProcessor

FILE_PATH = os.path.dirname(os.path.abspath(__file__))
scanner = Scanner(os.path.join(FILE_PATH, "../", "scripts/images/test_qr_ondular_200_5_0_2axes.png"),
                  threshold="simple",
                  output_size=1000,
                  output_border=100)

img = scanner.scan()[0].image
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
edges = cv2.Canny(gray, 50, 150, apertureSize=3)

img_plot = img.copy()

plt.figure()
plt.imshow(edges, interpolation="none", cmap="gray")

lines = cv2.HoughLines(edges, 1, np.pi/180, 120, None, 0, 0)
if lines is not None:
    for i in range(0, len(lines)):
        rho = lines[i][0][0]
        theta = lines[i][0][1]
        a = np.cos(theta)
        b = np.sin(theta)
        x0 = a * rho
        y0 = b * rho
        pt1 = (int(x0 + 1000 * (-b)), int(y0 + 1000 * (a)))
        pt2 = (int(x0 - 1000 * (-b)), int(y0 - 1000 * (a)))
        cv2.line(img_plot, pt1, pt2, (0, 0, 255), 3, cv2.LINE_AA)

plt.figure()
plt.imshow(img_plot, interpolation="none")


img_segments = img.copy()

pixels = 200

for ii in range(5):
    for jj in range(5):

        edges_segment = edges[ii*pixels:((ii+1)*pixels), jj*pixels:((jj+1)*pixels)]
        img_segment = img_segments[ii*pixels:((ii+1)*pixels), jj*pixels:((jj+1)*pixels)]

        lines = cv2.HoughLines(edges_segment, 1, np.pi / 180, 40, None, 0, 0)
        if lines is not None:
            for i in range(0, len(lines)):
                rho = lines[i][0][0]
                theta = lines[i][0][1]
                a = np.cos(theta)
                b = np.sin(theta)
                x0 = a * rho
                y0 = b * rho
                pt1 = (int(x0 + 1000 * (-b)), int(y0 + 1000 * (a)))
                pt2 = (int(x0 - 1000 * (-b)), int(y0 - 1000 * (a)))
                cv2.line(img_segment, pt1, pt2, (25, 0, int((ii*5 + jj)*255/25)), 3, cv2.LINE_AA)

        img_segments[ii*pixels:((ii+1)*pixels), jj*pixels:((jj+1)*pixels)] = img_segment

plt.figure()
plt.imshow(img_segments, interpolation="none")
plt.show()