import numpy as np
import cv2


def gammaCorrection(v):
    if v <= 0.04045 * 255:
        return (v / 255) / 12.92
    elif v > 0.04045 * 255:
        return (((v / 255) + 0.055) / 1.055) ** 2.4


def reverseGammaCorrection(v_reverse):
    if abs(v_reverse) <= 0.0031308:
        return round(255 * (12.92 * abs(v_reverse)))
    elif abs(v_reverse) > 0.0031308:
        if (round(255 * (1.055 * abs(v_reverse) ** 0.41666 - 0.055))) > 255:
            return 255
        else:
            return round(255 * (1.055 * abs(v_reverse) ** 0.41666 - 0.055))


class Dyschromasie:
    cb_image = np.array([]).astype('float64')
    sim_image = np.array([]).astype('uint8')

    def __init__(self, img_mat=np.array([]), rows=0, cols=0, kanaele=0, sim_faktor=0, sim_kind='d'):
        self.rows = rows
        self.cols = cols
        self.kanaele = kanaele
        self.img_mat = img_mat
        self.sim_faktor = sim_faktor
        self.sim_kind = sim_kind

    T = np.array([[0.31399022, 0.63951294, 0.04649755],
                  [0.15537241, 0.75789446, 0.08670142],
                  [0.01775239, 0.10944209, 0.87256922]])

    T_reversed = np.array([[5.47221206, -4.6419601, 0.16963708],
                           [-1.1252419, 2.29317094, -0.1678952],
                           [0.02980165, -0.19318073, 1.16364789]])

    def Simulate(self):
        if self.sim_kind == 'p':
            sim_mat = np.array([[(1 - self.sim_faktor), 1.05118294 * self.sim_faktor, -0.05116099 * self.sim_faktor],
                                [0, 1, 0],
                                [0, 0, 1]])
        elif self.sim_kind == 'd':
            sim_mat = np.array([[1, 0, 0],
                                [0.9513092 * self.sim_faktor, (1 - self.sim_faktor), 0.04866992 * self.sim_faktor],
                                [0, 0, 1]])
        else:
            sim_mat = np.array([[1, 0, 0],
                                [0, 1, 0],
                                [-0.86744736 * self.sim_faktor, 1.86727089 * self.sim_faktor, (1 - self.sim_faktor)]])

        # Gammakorrektur durchfuehren
        self.cb_image = np.copy(self.img_mat).astype('float64')

        for i in range(self.rows):
            for j in range(self.cols):
                for x in range(3):
                    self.cb_image[i, j, x] = gammaCorrection(self.img_mat[i, j, x])

        rechen_Mat = np.copy(self.T_reversed.dot(sim_mat).dot(self.T))
        
        # Einzelne Pixelwertberechnung
        for i in range(self.rows):
            for j in range(self.cols):
                self.cb_image[i, j] = rechen_Mat.dot(self.cb_image[i, j])

        self.sim_image = np.copy(self.cb_image)
        self.sim_image = self.sim_image.astype('uint8')
        # Rücktransformation der Gammawerte
        for i in range(self.rows):
            for j in range(self.cols):
                for x in range(3):
                    self.sim_image[i, j, x] = reverseGammaCorrection(self.cb_image[i, j, x])

        return self.sim_image
