from flask import Blueprint, request, jsonify, g
from werkzeug.datastructures import MultiDict
import os
import uuid
from config import DEFAULT_COURSE_COVER
from db.model import db, Course, Category, User, Chat
from utils.utils import random_string_generator
from utils.auth import auth_required, requires_role
from constants import *
from config import *
from constants import PublishedStatus

course = Blueprint('course', __name__)

@course.route('/create', methods=['POST'])
@auth_required()
def create_course():
    form_data: dict  = request.form
    course_uploaded_cover_image: MultiDict|None = request.files.get('cover_image', None)
    course_uploaded_pdf: MultiDict|None = request.files.get('course_pdf', None)

    cover_file_name: str = DEFAULT_COURSE_COVER
    pdf_file_name: str = ''
    if course_uploaded_cover_image is not None:
        cover_file_name: str = random_string_generator(32)+course_uploaded_cover_image.filename.split('.')[-1]
        course_uploaded_cover_image.save(os.path.join(USER_UPLOADS_DIR, cover_file_name))
    if course_uploaded_pdf is not None:
        pdf_file_name: str = random_string_generator(32) + course_uploaded_pdf.filename.split('.')[-1]
        course_uploaded_pdf.save(os.path.join(USER_UPLOADS_DIR, pdf_file_name))
    published_status: PublishedStatus = PublishedStatus.DRAFT
    try:
        course_name: str = form_data['course_name']
    except KeyError:
        return jsonify({'message': 'Course name cannot be empty'}), 401

    course_description: str = form_data.get('course_description', '')
    category_id: uuid.UUID = uuid.UUID(form_data['category_uuid'])
    pages_required_for_community: int = int(form_data['community_unlock_at_pages'])  # TODO: Add this field to model

    new_course: Course = Course(
        name=course_name,
        categoryID=category_id,
        authorID=g.current_user.id,
        description=course_description,
        isActive=True,
        publishedStatus=int(published_status),
        coverImage=cover_file_name,
        serverFilename =pdf_file_name,
        enrollments=[],
        quizzes=[],
        chats=[]
    )
    # chat: Chat = Chat(courseID=new_course.id) TODO: Add a welcome chat for this course
    db.session.add_all(new_course)
    db.session.commit()
    return jsonify({'message': 'Course was created successfully.'}), 200