import io
import zipfile
from django.shortcuts import render
import numpy as np
import os
import cv2

from django.conf import settings
# Create your views here.
from django.shortcuts import redirect

from django.http import HttpResponse


def index(request):
    return HttpResponse("Hello, world. You're at the polls index.")

def home(request):
    return render(request, 'index.html')


def transform(request):
    return render(request, 'transformacao.html')


def read_directories(directory):
    # Get a list of filenames in the specified directory
    filenames = []
    for filename in os.listdir(directory):
      filenames.append(filename)
    return filenames


def detecta_borda_principal(image):

    # Apply edge detection using Canny algorithm
    edges = cv2.Canny(image, 50, 150)

    # Find contours from the edges detected
    contours, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

    # Create an empty image to draw the contours
    contour_image = np.zeros_like(image)

    # Draw the largest contour which is likely to be the main border
    if contours:
        largest_contour = max(contours, key=cv2.contourArea)
        cv2.drawContours(contour_image, [largest_contour], -1, (255, 255, 255), 2)

    return image, contour_image, contours


def calculate_main_border_angle(contour):
    # Fit a bounding box to the contour
    rect = cv2.minAreaRect(contour)
    box = cv2.boxPoints(rect)
    box = np.intp(box)

    # Calculate the angle
    angl = rect[2]
  
    if angl > 45:        
        new = -(90-angl)
        return new, box
    else:       
        new = angl
        return new, box

def retorna_menor(vetor):    
    x,y = vetor[0]
    x1,y1 = vetor[1]    
    soma = x + y
    soma1 = x1 + y1
    if soma < soma1:
        menor = vetor[0]   
    else:
      menor = vetor[1]   
    return menor

def ler_pasta(request):   
    
     import pdb; pdb.set_trace()
          
     if request.method == 'GET':
         return render(request, 'transformacao.html')
     elif request.method == 'POST':
        
        files = request.FILES.getlist('gabaritos[]')
        zip_buffer = io.BytesIO()
        
        # Crie um arquivo ZIP em memória
        with zipfile.ZipFile(zip_buffer, 'w') as zip_file:
            for file in files:               
                
               
                file_bytes = file.read()

                # Converter bytes para um array numpy
                np_arr = np.frombuffer(file_bytes, np.uint8)

                # Decodificar a imagem do array numpy
                image = cv2.imdecode(np_arr, cv2.IMREAD_GRAYSCALE)

                # Apply GaussianBlur to reduce noise and improve edge detection
                blurred_image = cv2.GaussianBlur(image, (5, 5), 0)

                image_resized = cv2.resize(blurred_image, (794, 1123))

                original_image, contour_image, contours = detecta_borda_principal(image_resized)

                # Get the largest contour, which is the main border
                if contours:
                    largest_contour = max(contours, key=cv2.contourArea)
                    angle, box = calculate_main_border_angle(largest_contour)    
                else:
                    angle = None


                # Rotacionar a imagem em graus
                (h, w) = image_resized.shape[:2]
                center = (w // 2, h // 2)
                rotation_matrix = cv2.getRotationMatrix2D(center, (angle), 1.0)
                rotated_image = cv2.warpAffine(image_resized, rotation_matrix, (w, h))


                original_image, contour_image, contours = detecta_borda_principal(rotated_image)

                largest_contour = max(contours, key=cv2.contourArea)
                angle, box = calculate_main_border_angle(largest_contour)    
                    
                minimo = retorna_menor(box)   

                linha = minimo[1]
                coluna = minimo[0]

                cropped_rect = rotated_image[linha+5:1065, coluna+5:765]              
                         
                # Codifique a imagem de volta para formato PNG
                _, buffer = cv2.imencode('.png', cropped_rect)

                # Adicione a imagem modificada ao arquivo ZIP
                zip_file.writestr(f'{file.name}', buffer.tobytes())

        # Configure o buffer do ZIP para o início
        zip_buffer.seek(0)

        # Crie uma resposta HTTP com o conteúdo do arquivo ZIP
        response = HttpResponse(zip_buffer, content_type='application/zip')
        response['Content-Disposition'] = 'attachment; filename="modified_images.zip"'        
        
        
        return response