"""Equipments Restrictions Routes - GMAO Collège"""
from flask import Blueprint, render_template, redirect, url_for, request, flash, jsonify
from flask_login import login_required, current_user
from datetime import datetime
from app_new.extensions import db
from ..core.models.equipment import Equipment, EquipmentCategory, EquipmentDocument, EquipmentRoomHistory, EquipmentRestriction
from ..core.models.college import Room, Building, RoomType, Zone
from ..core.models.maintenance import Lot, Intervention
from ..core.models.planning import Meter, MeterReading, Consumable, EquipmentConsumable, ScheduledTask
from app_new.constants import EQUIPMENT_STATUSES

def _empty_to_none(v):
    """Convertit une chaîne vide en None."""
    return None if v == '' else v

restrictions_bp = Blueprint("equipments_restrictions", __name__, template_folder='templates')

@restrictions_bp.route('/<int:id>/restrictions')
@login_required
def restrictions(id):
    """Liste des restrictions d'un équipement."""
    from ..core.models.equipment import EquipmentRestriction
    from ..core.models.college import Room
    
    equipment = Equipment.query.get_or_404(id)
    restrictions = EquipmentRestriction.query.filter_by(equipment_id=id).all()
    rooms = Room.query.order_by(Room.name).all()
    days = {0: 'Dimanche', 1: 'Lundi', 2: 'Mardi', 3: 'Mercredi', 4: 'Jeudi', 5: 'Vendredi', 6: 'Samedi'}
    
    return render_template('equipments/restrictions.html', 
                          equipment=equipment, 
                          restrictions=restrictions,
                          rooms=rooms,
                          days=days)


@restrictions_bp.route('/<int:id>/restrictions/new', methods=['GET', 'POST'])
@login_required
def new_restriction(id):
    """Ajouter une restriction à un équipement."""
    from ..core.models.equipment import EquipmentRestriction
    from ..core.models.college import Room
    from flask_login import current_user
    
    equipment = Equipment.query.get_or_404(id)
    
    if request.method == 'POST':
        restriction_type = request.form.get('restriction_type')
        
        if restriction_type == 'time':
            # Restriction par horaire
            start_time = datetime.strptime(request.form.get('start_time'), '%H:%M').time() if request.form.get('start_time') else None
            end_time = datetime.strptime(request.form.get('end_time'), '%H:%M').time() if request.form.get('end_time') else None
            days = request.form.getlist('days')
            
            restriction = EquipmentRestriction(
                equipment_id=id,
                restriction_type='time',
                start_time=start_time,
                end_time=end_time,
                days_of_week=','.join(days) if days else None,
                message=request.form.get('message'),
                created_by_id=current_user.id
            )
        else:
            # Restriction par occupation de salle
            room_ids = request.form.getlist('room_ids')
            
            # Créer une restriction par salle sélectionnée
            for room_id in room_ids:
                restriction = EquipmentRestriction(
                    equipment_id=id,
                    restriction_type='room_occupancy',
                    room_id=int(room_id),
                    message=request.form.get('message'),
                    created_by_id=current_user.id
                )
                db.session.add(restriction)
            
            db.session.commit()
            flash('Restrictions ajoutées', 'success')
            return redirect(url_for('equipments.restrictions', id=id))
        
        db.session.add(restriction)
        db.session.commit()
        flash('Restriction ajoutée', 'success')
        return redirect(url_for('equipments.restrictions', id=id))
    
    rooms = Room.query.order_by(Room.name).all()
    days = {0: 'Dimanche', 1: 'Lundi', 2: 'Mardi', 3: 'Mercredi', 4: 'Jeudi', 5: 'Vendredi', 6: 'Samedi'}
    
    return render_template('equipments/restriction_form.html',
                          equipment=equipment,
                          rooms=rooms,
                          days=days)


@restrictions_bp.route('/<int:id>/restrictions/<int:restriction_id>/delete', methods=['POST'])
@login_required
def delete_restriction(id, restriction_id):
    """Supprimer une restriction."""
    from ..core.models.equipment import EquipmentRestriction
    
    restriction = EquipmentRestriction.query.filter_by(
        id=restriction_id, equipment_id=id
    ).first_or_404()
    db.session.delete(restriction)
    db.session.commit()
    flash('Restriction supprimée', 'success')
    return redirect(url_for('equipments.restrictions', id=id))

