# Copyright 2018-2026 Jérôme Dumonteil
# Copyright (c) 2009-2010 Ars Aperta, Itaapy, Pierlis, Talend.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
#
# Authors (odfdo project): jerome.dumonteil@gmail.com
# The odfdo project is a derivative work of the lpod-python project:
# https://github.com/lpod/lpod-python
# Authors: Hervé Cauwelier <herve@itaapy.com>
#          David Versmisse <david.versmisse@itaapy.com>

from datetime import date, time
from sys import version_info

from PIL import Image

from odfdo import (
    Document,
    Frame,
    Header,
    Paragraph,
    Style,
    Table,
    UserFieldDecl,
    VarChapter,
    VarDate,
    VarDecl,
    VarGet,
    VarPageCount,
    VarPageNumber,
    VarSet,
    VarTime,
    __version__,
    rgb2hex,
)


def use_case1(destination_file, source_path):
    print("odfdo test use case 2")
    print(f"version: {__version__}")
    print(f"Generating test file {destination_file}")

    document = Document("text")
    body = document.body

    # 0- The image
    # ------------
    image = Image.open(source_path)
    width, height = image.size
    # Add the image
    image_uri = document.add_file(source_path)
    draw_size = (f"{width / 100:.2f}cm", f"{height / 100:.2f}cm")
    image_frame = Frame.image_frame(
        image_uri,
        size=draw_size,
        position=("0cm", "0cm"),
    )
    paragraph = Paragraph("", style="Standard")
    paragraph.append(image_frame)
    body.append(paragraph)
    body.append(Paragraph())

    # 1- Congratulations (=> style on paragraph)
    # ------------------------------------------
    heading = Header(1, text="Congratulations !")
    body.append(heading)

    # The style
    style = Style(
        "paragraph",
        "style1",
        parent_style="Standard",
        area="text",
        color=rgb2hex("blue"),
        background_color=rgb2hex("red"),
    )
    document.insert_style(style)

    # The paragraph
    text = "This document has been generated by the odfdo installation test."
    paragraph = Paragraph(text, style="style1")
    body.append(paragraph)

    # 2- Your environment (=> a table)
    # --------------------------------
    heading = Header(1, text="Your environment")
    body.append(heading)

    data = []

    # lpOD Version
    data.append(["odfdo library version", __version__])

    # Python version
    data.append(
        [
            "Python version",
            f"{version_info.major}.{version_info.minor}.{version_info.micro}",
        ]
    )

    # Creation / Insertion
    table = Table("table1", width=2, height=2, style="Standard")
    table.set_values(data)
    body.append(table)

    # 3- Description (=> footnote & => highlight)
    # -------------------------------------------

    heading = Header(1, text="Description")
    body.append(heading)

    # A paragraph with a note
    text = "The odfdo project is made to generate ODF documents."
    paragraph = Paragraph(text, style="Standard")
    paragraph.insert_note(
        after="odfdo project",
        note_id="note1",
        citation="1",
        body="https://github.com/jdum/odfdo",
    )
    body.append(paragraph)

    # A paragraph with a highlighted word

    # The style
    style = Style(
        "text",
        "style2",
        parent_style="Standard",
        area="text",
        background_color=rgb2hex("yellow"),
    )
    document.insert_style(style)

    # The paragraph
    text = (
        "The office document file format OpenDocument Format (ODF) "
        "is an ISO standard ISO 26300 used by many applications."
    )
    paragraph = Paragraph(text, "Standard")
    paragraph.set_span("style2", regex="ISO standard")
    body.append(paragraph)

    # 4- A variable
    # -------------

    # A variable "spam" with the value 42
    variable_set = VarSet("spam", 42)
    value_type = variable_set.get_attribute("office:value-type")
    variable_decl = VarDecl("spam", value_type)

    # Insert
    heading = Header(1, text="A variable")
    body.append(heading)

    decl = body.get_variable_decls()
    decl.append(variable_decl)

    text = "The value of spam is:"
    value = body.get_variable_set_value("spam")
    variable_get = VarGet("spam", value)
    paragraph = Paragraph(text, style="Standard")
    body.append(paragraph)
    paragraph.insert_variable(variable_get, "is:")

    # 5- An user field
    # ----------------

    # An user field "pi5" with the value 3.14159
    user_field_decl = UserFieldDecl("pi5", value=3.14159)

    # Insert
    heading = Header(1, text="A user field")
    body.append(heading)

    decl = body.get_user_field_decls()
    decl.append(user_field_decl)

    text = "The value of pi5 is: "
    value = body.get_user_field_value("pi5")
    paragraph = Paragraph(text, style="Standard")
    body.append(paragraph)

    # 6- Page number
    # --------------

    heading = Header(1, text="Page number")
    body.append(heading)

    text1 = "The current page is: "
    text2 = "The previous page is: "
    text3 = "The next page is: "
    text4 = "The total page number is: "

    paragraph = Paragraph(text1, style="Standard")
    body.append(paragraph)
    paragraph.insert_variable(VarPageNumber(), "is:")

    paragraph = Paragraph(text2, style="Standard")
    body.append(paragraph)
    paragraph.insert_variable(VarPageNumber(select_page="previous"), "is:")

    paragraph = Paragraph(text3, style="Standard")
    body.append(paragraph)
    paragraph.insert_variable(VarPageNumber(select_page="next"), "is:")

    paragraph = Paragraph(text4, style="Standard")
    body.append(paragraph)
    paragraph.insert_variable(VarPageCount(), "is:")

    # 7- Date
    # -------

    heading = Header(1, text="Date insertion")
    body.append(heading)

    text1 = "A fixed date: "
    text2 = "Today: "

    paragraph = Paragraph(text1, style="Standard")
    body.append(paragraph)
    paragraph.insert_variable(VarDate(date(2009, 7, 20), fixed=True), "date:")

    paragraph = Paragraph(text2, style="Standard")
    body.append(paragraph)
    paragraph.insert_variable(VarDate(date(2009, 7, 20)), "Today:")

    # 8- Time
    # --------

    heading = Header(1, text="Time insertion")
    body.append(heading)

    text1 = "A fixed time: "
    text2 = "Now: "

    paragraph = Paragraph(text1, style="Standard")
    body.append(paragraph)
    paragraph.insert_variable(VarTime(time(19, 30), fixed=True), "time:")

    paragraph = Paragraph(text2, style="Standard")
    body.append(paragraph)
    paragraph.insert_variable(VarTime(time(19, 30)), "Now:")

    # 9- Chapter
    # -----------

    heading = Header(1, text="Chapter")
    body.append(heading)

    text = "The current chapter is: "

    paragraph = Paragraph(text, style="Standard")
    body.append(paragraph)
    paragraph.insert_variable(VarChapter(display="number-and-name"), "is:")

    # 10- Filename
    # ------------

    heading = Header(1, text="Filename")
    body.append(heading)

    text = "The current file name is: "

    paragraph = Paragraph(text, style="Standard")
    body.append(paragraph)

    # Save
    # ----

    destination_file.parent.mkdir(parents=True, exist_ok=True)
    document.save(destination_file, pretty=True)


def test_use_case2(tmp_path, samples):
    path = tmp_path / "use_case_2.odt"
    image_path = samples("image.png")
    use_case1(path, image_path)
    assert path.is_file()
