from flask import Blueprint, jsonify, request, abort, render_template, redirect, url_for, flash
from flask_login import login_required, current_user
from models import db, Room, User, RoomMemberPermission, Notif
from utils import user_has_permission, log_event, create_notification, get_unread_count
from routes.auth import require_password_change
from datetime import datetime

room_members_bp = Blueprint('room_members', __name__, url_prefix='/api/rooms')

@room_members_bp.context_processor
def inject_unread_notifications():
    if current_user.is_authenticated:
        unread_count = get_unread_count(current_user.id)
        return {'unread_notifications': unread_count}
    return {'unread_notifications': 0}

@room_members_bp.route('/<int:room_id>/members', methods=['GET'])
@login_required
def list_room_members(room_id):
    room = Room.query.get_or_404(room_id)
    if not user_has_permission(room, 'can_view'):
        abort(403)
    
    members = []
    for member in room.members:
        permission = RoomMemberPermission.query.filter_by(room_id=room_id, user_id=member.id).first()
        members.append({
            'id': member.id,
            'username': member.username,
            'last_name': member.last_name,
            'email': member.email,
            'profile_picture': member.profile_picture,
            'permissions': {
                'can_view': permission.can_view if permission else False,
                'can_download': permission.can_download if permission else False,
                'can_upload': permission.can_upload if permission else False,
                'can_delete': permission.can_delete if permission else False,
                'can_rename': permission.can_rename if permission else False,
                'can_move': permission.can_move if permission else False,
                'can_share': permission.can_share if permission else False
            }
        })
    
    return jsonify(members)

@room_members_bp.route('/<int:room_id>/members', methods=['POST'])
@login_required
def add_room_member(room_id):
    room = Room.query.get_or_404(room_id)
    if not user_has_permission(room, 'can_share'):
        abort(403)
    
    data = request.get_json()
    user_id = data.get('user_id')
    permissions = data.get('permissions', {})
    
    if not user_id:
        return jsonify({'error': 'User ID is required'}), 400
    
    user = User.query.get_or_404(user_id)
    
    # Add user to room members
    if user not in room.members:
        room.members.append(user)
    
    # Update permissions
    permission = RoomMemberPermission.query.filter_by(room_id=room_id, user_id=user_id).first()
    if not permission:
        permission = RoomMemberPermission(room_id=room_id, user_id=user_id)
        db.session.add(permission)
    
    permission.can_view = permissions.get('can_view', True)
    permission.can_download = permissions.get('can_download', False)
    permission.can_upload = permissions.get('can_upload', False)
    permission.can_delete = permissions.get('can_delete', False)
    permission.can_rename = permissions.get('can_rename', False)
    permission.can_move = permissions.get('can_move', False)
    permission.can_share = permissions.get('can_share', False)
    
    try:
        # Create notification for the invited user
        create_notification(
            notif_type='room_invite',
            user_id=user_id,
            sender_id=current_user.id,
            details={
                'message': f'You have been invited to join room "{room.name}"',
                'room_id': room_id,
                'room_name': room.name,
                'invited_by': f"{current_user.username} {current_user.last_name}",
                'permissions': permissions,
                'timestamp': datetime.utcnow().isoformat()
            }
        )
        
        log_event(
            event_type='room_member_add',
            details={
                'room_id': room_id,
                'room_name': room.name,
                'added_user_id': user_id,
                'added_user_name': f"{user.username} {user.last_name}",
                'added_by': f"{current_user.username} {current_user.last_name}"
            },
            user_id=current_user.id
        )

        db.session.commit()
        return jsonify({'success': True})
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500

@room_members_bp.route('/<int:room_id>/members/<int:user_id>', methods=['DELETE'])
@login_required
def remove_room_member(room_id, user_id):
    room = Room.query.get_or_404(room_id)
    if not user_has_permission(room, 'can_share'):
        abort(403)
    
    user = User.query.get_or_404(user_id)
    
    # Remove user from room members
    if user in room.members:
        room.members.remove(user)
    
    # Remove permissions
    permission = RoomMemberPermission.query.filter_by(room_id=room_id, user_id=user_id).first()
    if permission:
        db.session.delete(permission)
    
    try:
        # Create notification for the removed user
        create_notification(
            notif_type='room_invite_removed',
            user_id=user_id,
            sender_id=current_user.id,
            details={
                'message': f'You have been removed from room "{room.name}"',
                'room_id': room_id,
                'room_name': room.name,
                'removed_by': f"{current_user.username} {current_user.last_name}",
                'timestamp': datetime.utcnow().isoformat()
            }
        )
        
        log_event(
            event_type='room_member_remove',
            details={
                'room_id': room_id,
                'room_name': room.name,
                'removed_user_id': user_id,
                'removed_user_name': f"{user.username} {user.last_name}",
                'removed_by': f"{current_user.username} {current_user.last_name}"
            },
            user_id=current_user.id
        )

        db.session.commit()
        return jsonify({'success': True})
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500

@room_members_bp.route('/<int:room_id>/members/<int:user_id>/permissions', methods=['PUT'])
@login_required
def update_member_permissions(room_id, user_id):
    room = Room.query.get_or_404(room_id)
    if not user_has_permission(room, 'can_share'):
        abort(403)
    
    data = request.get_json()
    permissions = data.get('permissions', {})
    
    permission = RoomMemberPermission.query.filter_by(room_id=room_id, user_id=user_id).first()
    if not permission:
        return jsonify({'error': 'User is not a member of this room'}), 404
    
    permission.can_view = permissions.get('can_view', permission.can_view)
    permission.can_download = permissions.get('can_download', permission.can_download)
    permission.can_upload = permissions.get('can_upload', permission.can_upload)
    permission.can_delete = permissions.get('can_delete', permission.can_delete)
    permission.can_rename = permissions.get('can_rename', permission.can_rename)
    permission.can_move = permissions.get('can_move', permission.can_move)
    permission.can_share = permissions.get('can_share', permission.can_share)
    
    db.session.commit()
    
    log_event(
        event_type='room_member_permissions_update',
        details={
            'room_id': room_id,
            'room_name': room.name,
            'user_id': user_id,
            'user_name': f"{permission.user.username} {permission.user.last_name}",
            'updated_by': f"{current_user.username} {current_user.last_name}",
            'old_permissions': {
                'can_view': permission.can_view,
                'can_download': permission.can_download,
                'can_upload': permission.can_upload,
                'can_delete': permission.can_delete,
                'can_rename': permission.can_rename,
                'can_move': permission.can_move,
                'can_share': permission.can_share
            },
            'new_permissions': permissions
        },
        user_id=current_user.id
    )

    db.session.commit()
    
    return jsonify({'success': True}) 