from re import A
from flask import Blueprint, request, jsonify, send_from_directory
from database import Session
from models.models import EventMedia, MediaType
import os

eventmedia_bp = Blueprint('eventmedia', __name__, url_prefix='/api/eventmedia')

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')


def get_param(key, default=None):
    # Reihenfolge: form > json > args
    if request.form and key in request.form:
        return request.form.get(key, default)
    if request.is_json and request.json and key in request.json:
        return request.json.get(key, default)
    return request.args.get(key, default)

# --- FileManager: List, Create Folder, Rename, Delete, Move ---


@eventmedia_bp.route('/filemanager/operations', methods=['GET', 'POST'])
def filemanager_operations():
    action = get_param('action')
    path = get_param('path', '/')
    name = get_param('name')
    new_name = get_param('newName')
    target_path = get_param('targetPath')

    full_path = os.path.join(MEDIA_ROOT, path.lstrip('/'))

    print(action, path, name, new_name, target_path, full_path)  # Debug-Ausgabe

    if action == 'read':
        # List files and folders
        items = []
        for entry in os.scandir(full_path):
            items.append({
                'name': entry.name,
                'isFile': entry.is_file(),
                'size': entry.stat().st_size,
                'dateModified': entry.stat().st_mtime,
                'type': os.path.splitext(entry.name)[1][1:] if entry.is_file() else '',
                'hasChild': entry.is_dir()
            })
        return jsonify({'files': items, 'cwd': {'name': os.path.basename(full_path), 'path': path}})
    elif action == 'delete':
        for item in request.form.getlist('names[]'):
            item_path = os.path.join(full_path, item)
            if os.path.isdir(item_path):
                os.rmdir(item_path)
            else:
                os.remove(item_path)
        return jsonify({'success': True})
    elif action == 'rename':
        src = os.path.join(full_path, name)
        dst = os.path.join(full_path, new_name)
        os.rename(src, dst)
        return jsonify({'success': True})
    elif action == 'move':
        src = os.path.join(full_path, name)
        dst = os.path.join(MEDIA_ROOT, target_path.lstrip('/'), name)
        os.rename(src, dst)
        return jsonify({'success': True})
    elif action == 'create':
        os.makedirs(os.path.join(full_path, name), exist_ok=True)
        return jsonify({'success': True})
    else:
        return jsonify({'error': 'Unknown action'}), 400

# --- FileManager: Upload ---


@eventmedia_bp.route('/filemanager/upload', methods=['POST'])
def filemanager_upload():
    session = Session()
    # Korrigiert: Erst aus request.form, dann aus request.args lesen
    path = request.form.get('path') or request.args.get('path', '/')
    upload_path = os.path.join(MEDIA_ROOT, path.lstrip('/'))
    os.makedirs(upload_path, exist_ok=True)
    for file in request.files.getlist('uploadFiles'):
        file_path = os.path.join(upload_path, file.filename)
        file.save(file_path)
        ext = os.path.splitext(file.filename)[1][1:].lower()
        try:
            media_type = MediaType(ext)
        except ValueError:
            media_type = MediaType.other
        media = EventMedia(
            media_type=media_type,
            url=file.filename,
            file_path=os.path.relpath(file_path, MEDIA_ROOT)
        )
        session.add(media)
    session.commit()
    return jsonify({'success': True})

# --- FileManager: Download ---


@eventmedia_bp.route('/filemanager/download', methods=['GET'])
def filemanager_download():
    path = request.args.get('path', '/')
    names = request.args.getlist('names[]')
    # Nur Einzel-Download für Beispiel
    if names:
        file_path = os.path.join(MEDIA_ROOT, path.lstrip('/'), names[0])
        return send_from_directory(os.path.dirname(file_path), os.path.basename(file_path), as_attachment=True)
    return jsonify({'error': 'No file specified'}), 400

# --- FileManager: Get Image (optional, für Thumbnails) ---


@eventmedia_bp.route('/filemanager/get-image', methods=['GET'])
def filemanager_get_image():
    path = request.args.get('path', '/')
    file_path = os.path.join(MEDIA_ROOT, path.lstrip('/'))
    return send_from_directory(os.path.dirname(file_path), os.path.basename(file_path))

# --- EventMedia-API: Metadaten-Liste (wie gehabt) ---


@eventmedia_bp.route('', methods=['GET'])
def list_media():
    session = Session()
    media = session.query(EventMedia).all()
    return jsonify([m.to_dict() for m in media])

# --- EventMedia-API: Metadaten-Update ---


@eventmedia_bp.route('/<int:media_id>', methods=['PUT'])
def update_media(media_id):
    session = Session()
    media = session.query(EventMedia).get(media_id)
    if not media:
        return jsonify({'error': 'Not found'}), 404
    data = request.json
    media.url = data.get('title', media.url)
    media.message_content = data.get('description', media.message_content)
    # Event-Zuordnung ggf. ergänzen
    session.commit()
    return jsonify(media.to_dict())


@eventmedia_bp.route('/find_by_filename', methods=['GET'])
def find_by_filename():
    filename = request.args.get('filename')
    if not filename:
        return jsonify({'error': 'Missing filename'}), 400
    session = Session()
    # Suche nach exaktem Dateinamen in url oder file_path
    media = session.query(EventMedia).filter(
        (EventMedia.url == filename) | (
            EventMedia.file_path.like(f"%{filename}"))
    ).first()
    if not media:
        return jsonify({'error': 'Not found'}), 404
    return jsonify({
        'id': media.id,
        'file_path': media.file_path,
        'url': media.url
    })
