from pylatex import Document, Section, Subsection, Command, Figure, Tabular, Center
from pylatex.utils import italic, NoEscape
import pickle
import os

def generateReport(filenm):
    # Create a basic LaTeX document
    doc = Document()
    doc.packages.append(NoEscape(r'\usepackage{float}'))
    doc.packages.append(NoEscape(r'\usepackage{draftwatermark}'))
    doc.preamble.append(NoEscape(r'\SetWatermarkText{Geneated by trussit GUI}'))
    doc.preamble.append(NoEscape(r'\SetWatermarkScale{0.5}'))
    doc.preamble.append(NoEscape(r'\SetWatermarkColor[gray]{0.9}'))
    # Add a title to the document
    doc.preamble.append(Command('title', 'Truss Structure Analysis'))
    doc.preamble.append(Command('author', 'Generated by trussit | pip install trussit [kunalgokhe@gmail.com]'))
    doc.preamble.append(Command('date', NoEscape(r'\today')))
    doc.append(NoEscape(r'\maketitle'))

    # Add a section
    with doc.create(Section('Truss Design',numbering=False)):
        doc.append('The design of the structure is shown below.')
        with doc.create(Figure(position='h!')) as image:
            image.add_image('undeformed.png', width='300px')
            image.add_caption('Undeformed Structure.')

    # Add a subsection
    with doc.create(Section('Deformation Results',numbering=False)):
        doc.append('Undeformed with deformation of structure is shown below.')
        with doc.create(Figure(position='H')) as image:
            image.add_image('deformed.png', width='300px')
            image.add_caption('Deformed Structure.')

    with open('repogen/data.pickle', 'rb') as handle:
        U = pickle.load(handle)

    with doc.create(Center()) as centered:
        with centered.create(Tabular('|c|c|c|')) as table:
            table.add_hline()
            table.add_row(("Node", "Ux", "Uy"))
            table.add_hline()
            for i in range(len(U)):
                table.add_row((i+1,U[i][0],U[i][1]))
            table.add_hline()
    # Generate and save the PDF
    doc.generate_pdf('repogen/sample', clean_tex=True)
    doc.dumps()
    os.rename('repogen/sample.pdf',filenm)

