#  Copyright (c) 2025  Jeffrey Hsu - JITToolBox
#  #
#  This program is free software: you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation, either version 3 of the License, or
#  (at your option) any later version.
#  #
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#  #
#  You should have received a copy of the GNU General Public License
#  along with this program.  If not, see <https://www.gnu.org/licenses/>.

import pathlib
from copy import deepcopy

from docx import Document
from docx.enum.text import WD_BREAK
from docx.shared import Cm, Mm

from module.schema import Course, Student


class DocPaper:
    def __init__(self, filename: str = 'Paper', template_path: str = '../template/template.docx'):
        self._doc = Document()
        self._template = Document(template_path)
        self._filename = filename

        section = self._doc.sections[0]
        section.page_width = Mm(210)
        section.page_height = Mm(297)
        section.top_margin = Cm(2)
        section.bottom_margin = Cm(2)
        section.left_margin = Cm(2)
        section.right_margin = Cm(2)

    def add_paper(self, course: Course, student: Student):
        new_table = deepcopy(self._template.tables[0])

        para = self._doc.add_paragraph()
        para._p.addprevious(new_table._element)
        para.add_run().add_break(WD_BREAK.PAGE)

        data_list = {
            '%CNAME%': course.name,
            '%CLASS%': student.class_name,
            '%SNAME%': student.name,
            '%NO%': student.no,
            '%SO%': student.so,
            '%Q%': '\n'.join([f'\t{idx + 1}、{i.topic}' for idx, i in enumerate(student.picked_questions)])
        }

        # 替换表格中的占位符
        for row in new_table.rows:
            for cell in row.cells:
                for para in cell.paragraphs:
                    for run in para.runs:
                        for key, val in data_list.items():
                            if key in run.text:
                                run.text = run.text.replace(key, str(val))
                                break

    def save(self, path: str = './'):
        self._doc.save(str(pathlib.Path(path) / f"{self._filename}.docx"))


if __name__ == '__main__':
    ...
