from dbmodel import *
from markdown_pdf import MarkdownPdf, Section
from datetime import datetime
from collections.abc import Sequence
from pathlib import Path
from grader import get_grader

def error() -> list[Section]:
    return [Section('# No Filter selected')]


def get_pdf(class_id: int) -> tuple[MarkdownPdf, str]:
    clas = Class.get_by_id(class_id)
      
    # Create PDF 
    pdf = MarkdownPdf(toc_level=2, mode='gfm-like')
    pdf.meta['title'] = clas.name 
    pdf.meta['author'] = 'Learnlytics by @DerGrumpf'
    pdf.meta['producer'] = 'Learnlytics'
    pdf.meta['subject'] = f'Passed List - {clas.name}'
    pdf.meta['keywords'] = f'Passed List,{clas.name}'
    
    css = None
    with open('./learnlytics/pdf/document_style.css') as f:
        css = f.read()

    return (pdf, css)


def get_metadata(author: str) -> str:
    text = f'Author: {author}\n\n'

    date = datetime.now()
    text += f'Created: {date.strftime("%A %d.%m.%Y %H:%M")}\n\n'

    text += 'This document is system-generated and may not require manual signatures.\n'
    return text

def get_pdf_student(student_id: int, author: str, logo_file: Path = None) -> list[Section]:
    if student_id < 1:
        return Section('# No Student selected')
    sections = list()
    student = Student.get_by_id(student_id)
    study = Study.get_by_id(student.study_id)
    subs = list(Submission.select().where(Submission.student_id == student.id))

    grader = get_grader(student.grader)
    points = [sub.points for sub in subs]
    maxs = [sub.lecture_id.points for sub in subs]
    
    name = f'{student.prename} {student.surname}'
    passed = f'{name} has passed the course successfully.' if grader.has_passed_course(points, maxs) else f'{name} failed the course.'

    text = ''

    # Append Logo 
    if logo_file:
        text += f'![logo]({logo_file})\n'

    text += f'# {student.prename} {student.surname} - {student.class_id.name}\n'
    text += f'#### {study.name}\n\n'
    text += f'Gender: **{student.sex}**\n\n'
    s = sum(points)
    text += f'Score: **{int(s) if s.is_integer() else s}/{sum(maxs)}**\n\n'
    text += f'Percent: **{s/sum(maxs):.1%}**\n\n'
    text += f'Grade: {grader.get_final_grade(points, maxs)}\n\n'
    text += passed + '\n\n'

    text += '---\n\n'
    text += get_metadata(author)
    sections.append(Section(text))
    
    text = '# Lectures\n'
    text += '|Lecture|Submission|Passed?|\n'
    text += '|-|-|-|\n'    
    n = 0
    for sub in subs:
        text += f'|{sub.lecture_id.title}|{int(sub.points) if sub.points.is_integer() else sub.points}/{sub.lecture_id.points}|{grader.get_grade(sub.points, sub.lecture_id.points)}|\n'
        
        n += 1
        if n == 30:
            text += '---\n\n'
            sections.append(Section(text))
            n = 0 
            text = '# Lectures\n'
            text += '|Lecture|Submission|Passed?|\n'
            text += '|-|-|-|\n'         

    if text and n != 0:
        text += '---\n\n'
        sections.append(Section(text))

    return sections

def get_pdf_header_creator(class_id: int, filter: Sequence[str], author: str, logo_file: Path = None) -> Section:
    text = ''
    # Append Logo
    if logo_file:
        text += f'![logo]({logo_file})\n' 
    
    # Title
    text += f'# Passed List - {Class.get_by_id(class_id).name}\n'
    
    # Filters applied
    text += '#### Study Programms:\n' 
    for n, filter_el in enumerate(filter, start=1):
        text += f'{n}. {filter_el}\n'
    text += '---\n\n'

    # Metadata
    text += get_metadata(author)
    return Section(text)
