from flask import jsonify
from urllib.parse import unquote, urlparse


def get_topic_detail(request, Topic, Videos):
    data = request.get_json()

    query = data.get('title')
    topicId = data.get('topic_id', 0)
    
    topics = []
    if topicId:
        topic = Topic.query.get(topicId)
        if topic:
            topics = [topic]
    elif query:
        # Decode the URL-encoded string to get the actual title
        decoded_query = unquote(query)
        print(decoded_query)
        topics = Topic.query.filter(Topic.title == decoded_query).all()

    if topics:

        output = []

        for topic in topics:

            topic_data = {
                'id': topic.id,  # Corresponds to `id`
                # Corresponds to `course_id` (foreign key to the `courses` table)
                'course_id': topic.course_id,
                'title': topic.title,  # Corresponds to `title`
                'description': topic.description or None,  # Corresponds to `description`
                # Corresponds to `content_type` (e.g., 'video', 'article', etc.)
                'content_type': topic.content_type,
                'content_url': topic.content_url or None,  # Corresponds to `content_url`
                'order': topic.order,  # Corresponds to `order`
                # Corresponds to `duration_minutes` (in minutes)
                'duration_minutes': topic.duration_minutes or None,
                # Corresponds to `is_previewable` (boolean)
                'is_previewable': topic.is_previewable,
                # Corresponds to `status` ('active' or 'inactive')
                'status': topic.status,
                # Corresponds to `created_at`, formatted as ISO string
                'created_at': topic.created_at.strftime('%Y-%m-%dT%H:%M:%S') if topic.created_at else None,
                # Corresponds to `updated_at`, formatted as ISO string
                'updated_at': topic.updated_at.strftime('%Y-%m-%dT%H:%M:%S') if topic.updated_at else None,
            }

            from models.user import CourseNotesContent
            note = CourseNotesContent.query.filter_by(topic_id=topic.id).first()
            if note:
                topic_data['note_content'] = note.content
            else:
                topic_data['note_content'] = ""

            from models.user import CourseAudioContent
            audio = CourseAudioContent.query.filter_by(topic_id=topic.id).first()
            if audio:
                topic_data['audio_url'] = audio.file_path
            else:
                topic_data['audio_url'] = ""

            output.append(topic_data)
        videos = Videos.query.filter(Videos.topic_id == topicId).all()

        output_ii = []
        print(topicId)

        for use in videos:
            try:
                url_data = urlparse.urlparse(use.video_url)
                query = urlparse.parse_qs(url_data.query)
                video_id = query.get('v', [None])[0]
                thumbnail = f'https://img.youtube.com/vi/{video_id}/0.jpg' if video_id else ''
            except Exception:
                thumbnail = ''

            user_data = {
                'id': use.id,  # Corresponds to `id`
                'title': use.title,  # Corresponds to `title`
                'video_url': use.video_url,  # Corresponds to `video_url`
                'type': use.type,  # Corresponds to `type`
                # Corresponds to `description`, use None if not available
                'description': use.description or None,
                'credit': use.credit,  # Corresponds to `credit`
                'for_which': use.for_which,  # Corresponds to `for_which`
                # Corresponds to `level` (assumed to be 'beginner', 'intermediate', or 'advanced')
                'level': use.level,
                'image_url': thumbnail,  # Corresponds to `image_url`
                # Corresponds to `video_duration` (formatted as HH:MM:SS)
                'video_duration': str(use.video_duration),
                'count_exercises': use.count_exercises,  # Corresponds to `count_exercises`
                'count_students': use.count_students,  # Corresponds to `count_students`
                'count_plays': use.count_plays,  # Corresponds to `count_plays`
                'count_views': use.count_views,  # Corresponds to `count_views`
                'count_likes': use.count_likes,  # Corresponds to `count_likes`
                'count_comments': use.count_comments,  # Corresponds to `count_comments`
                # Corresponds to `short_description`
                'short_description': use.short_description,
                'course_id': use.course_id,  # Corresponds to `course_id`
                'is_live': use.is_live,  # Corresponds to `is_live` (boolean)
                'chat_id': use.chat_id,  # Corresponds to `chat_id`
                # Corresponds to `is_active` (boolean)
                'is_active': use.is_active,
                'free': use.free,  # Corresponds to `free` (boolean)
                # Corresponds to `created_at`
                'created_at': use.created_at.strftime('%Y-%m-%dT%H:%M:%S') if use.created_at else None,
                # Corresponds to `updated_at`
                'updated_at': use.updated_at.strftime('%Y-%m-%dT%H:%M:%S') if use.updated_at else None,
                # Corresponds to `topic_id` (assumed to be available)
                'topic_id': use.topic_id,
            }

            output.append(user_data)

        print(topics)
        return jsonify({'topic': output, 'videos': output_ii}), 200
    else:
        return jsonify({"response": "error: title or topic_id is required"}), 400
