##############################################################################
# ScoDoc
# Copyright (c) 1999 - 2023 Emmanuel Viennet.  All rights reserved.
# See LICENSE
##############################################################################

"""Génération d'un trombinoscope en doc
"""

import docx
from docx.shared import Mm
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.enum.table import WD_ALIGN_VERTICAL

from app.scodoc import sco_etud
from app.scodoc import sco_photos
import app.scodoc.sco_utils as scu
import sco_version


def trombino_doc(groups_infos):
    "Send photos as docx document"
    filename = f"trombino_{groups_infos.groups_filename}.docx"
    sem = groups_infos.formsemestre  # suppose 1 seul semestre
    PHOTO_WIDTH = Mm(25)
    N_PER_ROW = 5  # XXX should be in ScoDoc preferences

    document = docx.Document()
    document.add_heading(
        f"Trombinoscope {sem['titreannee']} {groups_infos.groups_titles}", 1
    )
    section = document.sections[0]
    footer = section.footer
    footer.paragraphs[
        0
    ].text = f"Généré par {sco_version.SCONAME} le {scu.timedate_human_repr()}"

    nb_images = len(groups_infos.members)
    table = document.add_table(rows=2 * (nb_images // N_PER_ROW + 1), cols=N_PER_ROW)
    table.allow_autofit = False

    for i, t in enumerate(groups_infos.members):
        li = i // N_PER_ROW
        co = i % N_PER_ROW
        img_path = (
            sco_photos.photo_pathname(t["photo_filename"], size="small")
            or sco_photos.UNKNOWN_IMAGE_PATH
        )
        cell = table.rows[2 * li].cells[co]
        cell.vertical_alignment = WD_ALIGN_VERTICAL.TOP
        cell_p, cell_f, cell_r = _paragraph_format_run(cell)
        cell_r.add_picture(img_path, width=PHOTO_WIDTH)

        # le nom de l'étudiant: cellules de lignes impaires
        cell = table.rows[2 * li + 1].cells[co]
        cell.vertical_alignment = WD_ALIGN_VERTICAL.TOP
        cell_p, cell_f, cell_r = _paragraph_format_run(cell)
        cell_r.add_text(sco_etud.format_nomprenom(t))
        cell_f.space_after = Mm(8)

    return scu.send_docx(document, filename)


def _paragraph_format_run(cell):
    "parag. dans cellule tableau"
    # inspired by https://stackoverflow.com/questions/64218305/problem-with-python-docx-putting-pictures-in-a-table
    paragraph = cell.paragraphs[0]
    fmt = paragraph.paragraph_format
    run = paragraph.add_run()

    fmt.space_before = Mm(0)
    fmt.space_after = Mm(0)
    fmt.line_spacing = 1.0
    fmt.alignment = WD_ALIGN_PARAGRAPH.CENTER

    return paragraph, fmt, run
