from PIL import Image
import cv2
import numpy as np


def pil_to_opencv(image):
    numpy_image = np.array(image)

    opencv_image = cv2.cvtColor(numpy_image, cv2.COLOR_RGB2BGR)

    return opencv_image


def opencv_to_pil(image):
    # Convert OpenCV BGR image to NumPy array
    numpy_image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

    # Convert NumPy array to PIL Image
    pil_image = Image.fromarray(numpy_image)

    return pil_image


def generate(image, algorithm_name):
    algorithm_functions = {
        "Sobel Edge Detection": sobel_edge_detection,
        "Canny Edge Detection": canny_edge_detection,
        "Hough Lines": hough_lines,
        "Laplacian Edge Detection": laplacian_edge_detection,
        "Contours Detection": contours_detection,
        "Prewitt Edge Detection": prewitt_edge_detection,
        "Gradient Magnitude": gradient_magnitude,
        "Corner Detection": corner_detection,
    }

    if algorithm_name in algorithm_functions:
        algorithm_function = algorithm_functions[algorithm_name]
        processed_image = algorithm_function(image)
    else:
        processed_image = ()

    return processed_image


def sobel_edge_detection(image):
    gray = pil_to_opencv(image)
    sobelx = cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=5)
    sobely = cv2.Sobel(gray, cv2.CV_64F, 0, 1, ksize=5)
    magnitude = np.sqrt(sobelx**2 + sobely**2)
    magnitude = np.uint8(magnitude)
    return magnitude


def canny_edge_detection(image):
    gray = pil_to_opencv(image)
    edges = cv2.Canny(gray, 50, 150, apertureSize=3)
    return edges


def hough_lines(image):
    gray = pil_to_opencv(image)
    edges = cv2.Canny(gray, 50, 150)
    lines = cv2.HoughLines(edges, 1, np.pi / 180, threshold=100)
    result = image.copy()
    for line in lines:
        rho, theta = line[0]
        a = np.cos(theta)
        b = np.sin(theta)
        x0 = a * rho
        y0 = b * rho
        x1 = int(x0 + 1000 * (-b))
        y1 = int(y0 + 1000 * (a))
        x2 = int(x0 - 1000 * (-b))
        y2 = int(y0 - 1000 * (a))
        cv2.line(result, (x1, y1), (x2, y2), (0, 0, 255), 2)
    print("passed")

    return result


def laplacian_edge_detection(image):
    gray = pil_to_opencv(image)
    laplacian = cv2.Laplacian(gray, cv2.CV_64F)
    laplacian = np.uint8(np.absolute(laplacian))
    return laplacian


def contours_detection(image):
    gray = pil_to_opencv(image)
    contours, _ = cv2.findContours(gray, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    result = np.zeros_like(image)

    cv2.drawContours(result, contours, -1, (0, 255, 0), 2)
    print("passed")

    return result


def prewitt_edge_detection(image):
    gray = pil_to_opencv(image)
    prewittx = cv2.filter2D(
        gray, cv2.CV_64F, np.array([[-1, 0, 1], [-1, 0, 1], [-1, 0, 1]])
    )
    prewitty = cv2.filter2D(
        gray, cv2.CV_64F, np.array([[-1, -1, -1], [0, 0, 0], [1, 1, 1]])
    )
    magnitude = np.sqrt(prewittx**2 + prewitty**2)
    magnitude = np.uint8(magnitude)
    return magnitude


def gradient_magnitude(image):
    gray = pil_to_opencv(image)
    sobelx = cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=5)
    sobely = cv2.Sobel(gray, cv2.CV_64F, 0, 1, ksize=5)
    magnitude = np.sqrt(sobelx**2 + sobely**2)
    magnitude = np.uint8(magnitude)
    print("passed")

    return magnitude


def corner_detection(image):
    gray = pil_to_opencv(image)
    corners = cv2.goodFeaturesToTrack(
        gray, maxCorners=100, qualityLevel=0.01, minDistance=10
    )
    result = np.zeros_like(image)
    corners = np.int0(corners)
    for i in corners:
        x, y = i.ravel()
        cv2.circle(result, (x, y), 3, 255, -1)
    print("passed")
    return result