import cv2
import matplotlib.pyplot as plt
import numpy as np
import peakutils
from lmfit.lineshapes import *


def gaussian(x, a, b, c):
    """
    Gaussian function
    :param x: profile length
    :param a: heigth of the curve's peak
    :param b: position of the peak
    :param c: full with at half maximum
    :return: y values for each x of the gaussian with a,b and c parameters
    """
    gaussian = a * np.exp(-(x - b) ** 2 / (2 * c ** 2))
    return gaussian


def func_to_opt(x, a0, b0, c0, a1, b1, c1):
    """
    Adjusts to 2 bell curve shape
    :return:
    :param x: x values, profile length
    :param a0: the height of the first curve's peak
    :param b0: position of the first center peak
    :param c0: full width at half maximum of the first bell
    :param a1: the height of the second curve's peak
    :param b1: position of the second center peak
    :param c1: full width at half maximum of the second bell
    :return:
    """
    return gaussian(x, a0, b0, c0) + gaussian(x, a1, b1, c1)


class StripCreator:

    def create(self, height):

        x = np.arange(886)
        g = func_to_opt(x, 0.5, 200,6, 0.2, 250, 6)
        g3 = np.repeat([g], height, axis=0)
        g3 = g3.astype(np.float32)
        #plt.figure()
        g = g.astype(np.float32)
        plt.imshow(g3)

        bgr = cv2.cvtColor(g, cv2.COLOR_GRAY2BGR)
        hsv = cv2.cvtColor(bgr, cv2.COLOR_BGR2HSV)

        hsv[:, :, 0] = 300
        hsv[:, :, 1] = hsv[:, :, 2]
        hsv[:, :, 2] = 1

        g2 = cv2.cvtColor(hsv, cv2.COLOR_HSV2BGR)
        g2 = np.repeat(g2, height, axis=1)

        g2 = cv2.normalize(g2, dst=None, alpha=0, beta=255, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_8UC3)
        plt.figure()
        res  = cv2.normalize(hsv[:, :, 1], dst=None, alpha=0, beta=255, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_8UC3)
        plt.plot(x, cv2.normalize(hsv[:, :, 1], dst=None, alpha=0, beta=255, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_8UC3))
        plt.show()
        #plt.figure()
        #plt.imshow(g2)
        cv2.imwrite('tirapvh3-6.png', g2)

        indexes = peakutils.indexes(g, thres=0.4, min_dist=2)
        print(res[250], res[200])
        print(res[200]/res[250] *100)


ss = StripCreator()
ss.create(59)