"""
Room Types Routes - GMAO Collège
Gestion des types de salles
"""
from flask import Blueprint, render_template, request, flash, redirect, url_for
from flask_login import login_required
from app_new.extensions import db
from ..core.forms import RoomTypeForm
from ..core.models.college import Room, RoomType

room_types_bp = Blueprint('room_types', __name__, template_folder='templates')

@room_types_bp.route('/')
@login_required
def index():
    """Liste des types de salles."""
    room_types = RoomType.query.order_by(RoomType.name).all()
    return render_template('room_types/index.html', room_types=room_types)

@room_types_bp.route('/new', methods=['GET', 'POST'])
@login_required
def new():
    """Créer un type de salle."""
    form = RoomTypeForm()
    if form.validate_on_submit():
        room_type = RoomType(
            name=form.name.data,
            description=form.description.data,
            color=form.color.data,
            is_teaching=form.is_teaching.data,
        )
        db.session.add(room_type)
        db.session.commit()
        flash('Type de salle créé.', 'success')
        return redirect(url_for('room_types.index'))
    return render_template('room_types/form.html', title='Nouveau type de salle', form=form, room_type=None)

@room_types_bp.route('/<int:id>/edit', methods=['GET', 'POST'])
@login_required
def edit(id):
    """Modifier un type de salle."""
    room_type = RoomType.query.get_or_404(id)
    form = RoomTypeForm(obj=room_type)
    if form.validate_on_submit():
        room_type.name = form.name.data
        room_type.description = form.description.data
        room_type.color = form.color.data
        room_type.is_teaching = form.is_teaching.data
        db.session.commit()
        flash('Type de salle mis à jour.', 'success')
        return redirect(url_for('room_types.index'))
    rooms_in_type = Room.query.filter_by(room_type_id=room_type.id).order_by(Room.name).all()
    rooms_without_type = Room.query.filter(Room.room_type_id.is_(None)).order_by(Room.name).all()
    return render_template('room_types/form.html', title='Modifier le type de salle', form=form,
                           room_type=room_type, rooms_in_type=rooms_in_type,
                           rooms_without_type=rooms_without_type)


@room_types_bp.route('/<int:id>/rooms', methods=['POST'])
@login_required
def add_rooms(id):
    room_type = RoomType.query.get_or_404(id)
    room_ids = request.form.getlist('room_ids', type=int)
    if room_ids:
        Room.query.filter(Room.id.in_(room_ids)).update(
            {Room.room_type_id: room_type.id}, synchronize_session=False
        )
        db.session.commit()
    flash(f'{len(room_ids)} salle(s) associée(s).', 'success')
    return redirect(url_for('room_types.edit', id=id))


@room_types_bp.route('/<int:type_id>/rooms/<int:room_id>/remove', methods=['POST'])
@login_required
def remove_room(type_id, room_id):
    room = Room.query.filter_by(id=room_id, room_type_id=type_id).first_or_404()
    room.room_type_id = None
    db.session.commit()
    flash('Salle retirée du type.', 'success')
    return redirect(url_for('room_types.edit', id=type_id))


@room_types_bp.route('/<int:id>/delete', methods=['POST'])
@login_required
def delete(id):
    room_type = RoomType.query.get_or_404(id)
    if room_type.rooms:
        flash('Ce type est encore utilisé par des salles.', 'warning')
        return redirect(url_for('room_types.index'))
    db.session.delete(room_type)
    db.session.commit()
    flash('Type de salle supprimé.', 'success')
    return redirect(url_for('room_types.index'))
