import cv2
import os

import matplotlib.pyplot as plt

from qrcode import QRColoredCode
from qrcode.util import ColorSet

from qrdecode.main import QRProcessor
from qrdecode.utils.biostrip import ColorLines, Biostrip, np
from qrdecode.utils.image import ImageProcessor
from pyctorama import TPSColorProcessor

if __name__ == '__main__':
    FILE_PATH = os.path.dirname(os.path.abspath(__file__))

    c = ColorSet()

    qr1 = QRColoredCode(color_set=c)
    qr1.add_data("AliciaMorales12345")

    im1 = qr1.make_image()

    qr2 = QRColoredCode(color_set=c)
    qr2.add_data("AliciaMorales78910")

    im2 = qr2.make_image()

    biostrip = Biostrip(os.path.join(FILE_PATH, "../", "scripts/images/2018-06-06-163719.jpg"),
                        threshold="simple",
                        output_size=300,
                        output_border=30)

    print(biostrip.scanner.image_processor.patterns.get("mean").find("position").centers)

    codes = biostrip.scanner.codes
    plt.figure()

    assert isinstance(codes[0], ImageProcessor)

    plt.subplot(3, 5, 1)
    plt.imshow(im1.get_image())
    plt.title("Original Image")

    plt.subplot(3, 5, 2)
    plt.imshow(codes[0].image[:, :, ::-1])
    plt.title("Position Trimmed Image")

    processor1 = QRProcessor(codes[0],
                             code_border=biostrip.output_border,
                             code_offset=biostrip.output_offset,
                             code_size=biostrip.output_size
                             )
    plt.subplot(3, 5, 3)
    plt.title("Threshold image for analysis")
    plt.imshow(processor1.image_processor.threshold(processor1.threshold).copy(),
               interpolation="none",
               cmap="gray")

    processor1.correct_alignment()
    # Or alternatively:
    #processor1.correct_fourth_corner()

    processor1.sample()

    plt.subplot(3, 5, 4)
    plt.title("Alignment corrected Image")
    plt.imshow(processor1.image[:, :, ::-1])

    plt.subplot(3, 5, 5)
    plt.title("Colored extracted Image.")
    plt.imshow(processor1.matrix, interpolation="none", cmap="gray")
    plt.imshow(cv2.cvtColor(processor1.colors, cv2.COLOR_BGR2RGB))
    src_rgb, dst_rgb = processor1.colors_extraction(qr1)
    tps = TPSColorProcessor(src_rgb, dst_rgb)
    img_corrected = tps.transform(biostrip.sliced)
    data = processor1.decode()

    assert isinstance(codes[1], ImageProcessor)

    plt.subplot(3, 5, 6)
    plt.imshow(im2.get_image())
    plt.title("Original Image")

    plt.subplot(3, 5, 7)
    plt.imshow(codes[1].image[:, :, ::-1])
    plt.title("Position Trimmed Image")

    processor2 = QRProcessor(codes[1],
                             code_border=biostrip.output_border,
                             code_offset=biostrip.output_offset,
                             code_size=biostrip.output_size
                             )
    plt.subplot(3, 5, 8)
    plt.title("Threshold image for analysis")
    plt.imshow(processor2.image_processor.threshold(processor2.threshold).copy(),
               interpolation="none",
               cmap="gray")

    processor2.correct_alignment()
    # Or alternatively:
    # processor.correct_fourth_corner()

    processor2.sample()

    plt.subplot(3, 5, 9)
    plt.title("Alignment corrected Image")
    plt.imshow(processor2.image[:, :, ::-1])

    plt.subplot(3, 5, 10)
    plt.title("Colored extracted Image.")
    plt.imshow(processor2.matrix, interpolation="none", cmap="gray")
    #plt.imshow(cv2.cvtColor(processor2.colors, cv2.COLOR_BGR2RGB))
    #src_rgb, dst_rgb = processor2.colors_extraction(qr2)
    #
    #tps = TPSColorProcessor(src_rgb, dst_rgb)
    cv2.imshow('not-corrected', biostrip.image)
    all_img_corrected = tps.transform(biostrip.image)
    cv2.imshow('corrected', all_img_corrected)

    data = processor2.decode()

    plt.show()

    # if datas[0] == "AliciaMorales78910":
    #     (h, w) = img.shape[:2]
    #     center = (w / 2, h / 2)
    #
    #     # rotate the image by 180 degrees
    #     M = cv2.getRotationMatrix2D(center, 180, 1.0)
    #     img_corrected= cv2.warpAffine(img_corrected, M, (w, h))
    #     plt.imshow(img_corrected)

    lines = ColorLines(img_corrected, model="pvoigt")
    lines.to_hsv()
    lines.solve()
    print(lines.result.fit_report())
    print('h2/h1= ')
    print(lines.result.values['ssheight']/lines.result.values['fheight'])
    x = np.arange(len(lines.profile))

    plt.subplot(3, 5, 11)
    plt.plot(x, lines.profile, 'bo')
    plt.plot(x, lines.result.init_fit, 'k--')
    plt.plot(x, lines.result.best_fit, 'r-')

    plt.subplot(3, 5, 12)
    plt.imshow(biostrip.image[:, :, ::-1])
    plt.title("Original Image")

    plt.show()

