from apps.home import blueprint
from flask import session, render_template, request
from flask_login import login_required, current_user
from jinja2 import TemplateNotFound
from os import path
from apps.authentication.models import ConfigUpdates
from apps.authentication.routes import convert_image_to_jpg, client
from datetime import datetime

@blueprint.route('/dashboard')
@login_required
def dashboard():
    users = ConfigUpdates.query.filter_by(user_id=current_user.id).all()

    profile_data = [
        {
            'insta_username': user.insta_username,
            'followers_count': user.followers_count,
            'following_count': user.following_count,
            'posts_count': user.posts_count
        } 
        for user in users
    ]
    session['profile_data'] = profile_data
        
    today_date = datetime.now().strftime("%d/%m/%Y")
    session['today_date'] = today_date

    return render_template(
        'home/dashboard.html',
        profile_data=profile_data, 
        today_date=today_date,  
        segment='dashboard', 
        user_id=current_user.id
    )
    
# Route dynamique sans .html dans l'URL
@blueprint.route('/<template>')
@login_required
def route_template(template):
    try:
        if not template.endswith('.html'):
            template += '.html'

        # Détecter le segment de la page (nom de la route actuelle)
        segment = get_segment(request)

        # Servir le fichier (si existe) dans app/templates/home/FILE.html
        return render_template("home/" + template, segment=segment)

    except TemplateNotFound:
        return render_template('home/page-404.html'), 404

    except:
        return render_template('home/page-500.html'), 500


def get_segment(request):
    try:
        segment = request.path.split('/')[-1]
        
        if segment == '':
            segment = 'dashboard'

        return segment

    except:
        return None
