# 事件蓝图
# 处理录音事件的查看和日历导出

from flask import Blueprint, jsonify, send_file
from flask_login import login_required, current_user
from src.clients import db
from src.models import Event, Recording
from src.services import generate_ics_content
import io

# 创建蓝图
event_bp = Blueprint('event', __name__)

@event_bp.route('/api/recording/<int:recording_id>/events', methods=['GET'])
@login_required
def get_recording_events(recording_id):
    """获取录音的所有事件"""
    recording = Recording.query.filter_by(id=recording_id, user_id=current_user.id).first()
    if not recording:
        return jsonify({'error': '录音不存在'}), 404
    
    events = Event.query.filter_by(recording_id=recording_id).all()
    return jsonify([{
        'id': e.id,
        'title': e.title,
        'start_time': e.start_time.isoformat() if e.start_time else None,
        'end_time': e.end_time.isoformat() if e.end_time else None,
        'location': e.location,
        'description': e.description,
        'recording_id': e.recording_id
    } for e in events])

@event_bp.route('/api/event/<int:event_id>/ics', methods=['GET'])
@login_required
def download_event_ics(event_id):
    """下载单个事件的ICS日历文件"""
    event = Event.query.get(event_id)
    if not event:
        return jsonify({'error': '事件不存在'}), 404
    
    # 检查权限
    recording = Recording.query.filter_by(id=event.recording_id, user_id=current_user.id).first()
    if not recording:
        return jsonify({'error': '无权访问'}), 403
    
    ics_content = generate_ics_content([event])
    
    buffer = io.BytesIO()
    buffer.write(ics_content.encode('utf-8'))
    buffer.seek(0)
    
    filename = f"{event.title.replace(' ', '_')}.ics"
    return send_file(
        buffer,
        mimetype='text/calendar',
        as_attachment=True,
        download_name=filename
    )

@event_bp.route('/api/recording/<int:recording_id>/events/ics', methods=['GET'])
@login_required
def download_all_events_ics(recording_id):
    """下载录音所有事件的ICS日历文件"""
    recording = Recording.query.filter_by(id=recording_id, user_id=current_user.id).first()
    if not recording:
        return jsonify({'error': '录音不存在'}), 404
    
    events = Event.query.filter_by(recording_id=recording_id).all()
    if not events:
        return jsonify({'error': '没有事件'}), 404
    
    ics_content = generate_ics_content(events)
    
    buffer = io.BytesIO()
    buffer.write(ics_content.encode('utf-8'))
    buffer.seek(0)
    
    filename = f"{recording.title.replace(' ', '_')}_events.ics"
    return send_file(
        buffer,
        mimetype='text/calendar',
        as_attachment=True,
        download_name=filename
    )
