from flask import Flask, render_template, request, redirect, url_for, flash, send_from_directory
import os
import requests
import math

app = Flask(__name__)
app.secret_key = 'your_secret_key'  # Troque para uma chave secreta segura

FOLDER_PATH = 'folder/faces'  # Caminho para a subpasta com os rostos cortados
API_URL = 'http://localhost:5000/cadastro'  # URL da API de cadastro de rostos
FILES_PER_PAGE = 8  # Grid de 2x4, ou seja, 8 arquivos por página

@app.route('/')
def index():
    return redirect(url_for('listar_rostos'))

@app.route('/listar_rostos')
@app.route('/listar_rostos/page/<int:page>')
def listar_rostos(page=1):
    image_files = [f for f in os.listdir(FOLDER_PATH) if f.endswith('.jpg')]
    total_files = len(image_files)
    total_pages = math.ceil(total_files / FILES_PER_PAGE)

    start = (page - 1) * FILES_PER_PAGE
    end = start + FILES_PER_PAGE
    images = image_files[start:end]

    # Calcula a faixa de páginas a serem exibidas
    page_range = range(max(1, page-2), min(page+3, total_pages+1))

    return render_template('listar_rostos.html', images=images, page=page, total_pages=total_pages, page_range=page_range)

@app.route('/cadastrar_pessoas', methods=['GET', 'POST'])
def cadastrar_pessoas():
    if request.method == 'POST':
        name = request.form['name']
        selected_images = request.form.getlist('selected_images')
        if not selected_images or not name:
            flash('Por favor, selecione imagens e insira um nome.', 'danger')
            return redirect(url_for('cadastrar_pessoas'))

        for image in selected_images:
            image_path = os.path.join(FOLDER_PATH, image)
            with open(image_path, 'rb') as img_file:
                files = {'image': img_file}
                data = {'name': name}
                response = requests.post(API_URL, files=files, data=data)

                if response.status_code == 201:
                    flash(f'{image} cadastrada com sucesso.', 'success')
                else:
                    flash(f'Erro ao cadastrar {image}: {response.json().get("error", "Erro desconhecido")}', 'danger')

        return redirect(url_for('listar_rostos'))

    return render_template('cadastrar_pessoas.html')

@app.route('/faces/<filename>')
def serve_image(filename):
    return send_from_directory(FOLDER_PATH, filename)

if __name__ == '__main__':
    app.run(host="0.0.0.0", debug=True, port=5001)
