"""
Tests for embedded template functionality
"""

import pytest
import tempfile
import os
from pyPhotoAlbum.project import Project, Page
from pyPhotoAlbum.template_manager import TemplateManager, Template
from pyPhotoAlbum.models import PlaceholderData, TextBoxData
from pyPhotoAlbum.page_layout import PageLayout


def test_embed_template_in_project():
    """Test embedding a template in a project"""
    # Create a project
    project = Project(name="Test Project")

    # Create a template manager with the project
    template_manager = TemplateManager(project=project)

    # Create a simple template
    template = Template(name="Test Template", description="A test template")
    placeholder = PlaceholderData(placeholder_type="image", x=10, y=10, width=100, height=100)
    template.add_element(placeholder)

    # Embed the template
    template_manager.embed_template(template)

    # Verify it's embedded
    assert "Test Template" in project.embedded_templates
    assert project.embedded_templates["Test Template"]["name"] == "Test Template"
    assert len(project.embedded_templates["Test Template"]["elements"]) == 1


def test_load_embedded_template():
    """Test loading an embedded template"""
    # Create a project
    project = Project(name="Test Project")

    # Create a template manager with the project
    template_manager = TemplateManager(project=project)

    # Create and embed a template
    template = Template(name="Test Template", description="A test template")
    placeholder = PlaceholderData(placeholder_type="image", x=10, y=10, width=100, height=100)
    template.add_element(placeholder)
    template_manager.embed_template(template)

    # Load the embedded template
    loaded_template = template_manager.load_template("Test Template")

    assert loaded_template.name == "Test Template"
    assert loaded_template.description == "A test template"
    assert len(loaded_template.elements) == 1


def test_list_embedded_templates():
    """Test listing embedded templates alongside filesystem templates"""
    # Create a project
    project = Project(name="Test Project")

    # Create a template manager with the project
    template_manager = TemplateManager(project=project)

    # Embed some templates
    for i in range(3):
        template = Template(name=f"Embedded_{i}")
        template_manager.embed_template(template)

    # List all templates
    templates = template_manager.list_templates()

    # Check embedded templates are listed with prefix
    embedded_templates = [t for t in templates if t.startswith("[Embedded]")]
    assert len(embedded_templates) == 3
    assert "[Embedded] Embedded_0" in templates
    assert "[Embedded] Embedded_1" in templates
    assert "[Embedded] Embedded_2" in templates


def test_embedded_template_priority():
    """Test that embedded templates take priority over filesystem templates"""
    # Create a project
    project = Project(name="Test Project")

    # Create a template manager with the project
    template_manager = TemplateManager(project=project)

    # Embed a template with a common name
    embedded_template = Template(name="Common", description="Embedded version")
    template_manager.embed_template(embedded_template)

    # Load by name without prefix (should get embedded version)
    loaded = template_manager.load_template("Common")
    assert loaded.description == "Embedded version"


def test_serialize_project_with_embedded_templates():
    """Test serializing a project with embedded templates"""
    # Create a project
    project = Project(name="Test Project")

    # Create a template manager with the project
    template_manager = TemplateManager(project=project)

    # Create and embed a template
    template = Template(name="Test Template", description="A test template")
    placeholder = PlaceholderData(placeholder_type="image", x=10, y=10, width=100, height=100)
    template.add_element(placeholder)
    template_manager.embed_template(template)

    # Serialize the project
    serialized = project.serialize()

    # Verify embedded templates are in serialization
    assert "embedded_templates" in serialized
    assert "Test Template" in serialized["embedded_templates"]
    assert serialized["embedded_templates"]["Test Template"]["name"] == "Test Template"


def test_deserialize_project_with_embedded_templates():
    """Test deserializing a project with embedded templates"""
    # Create a project with embedded template
    project = Project(name="Test Project")
    template_manager = TemplateManager(project=project)

    template = Template(name="Test Template", description="A test template")
    placeholder = PlaceholderData(placeholder_type="image", x=10, y=10, width=100, height=100)
    template.add_element(placeholder)
    template_manager.embed_template(template)

    # Serialize the project
    serialized = project.serialize()

    # Create a new project and deserialize
    new_project = Project(name="New Project")
    new_project.deserialize(serialized)

    # Verify embedded templates were restored
    assert "Test Template" in new_project.embedded_templates
    assert new_project.embedded_templates["Test Template"]["name"] == "Test Template"

    # Verify we can load the template from the new project
    new_template_manager = TemplateManager(project=new_project)
    loaded_template = new_template_manager.load_template("Test Template")
    assert loaded_template.name == "Test Template"
    assert len(loaded_template.elements) == 1


def test_auto_embed_on_apply():
    """Test that templates are automatically embedded when applied"""
    # Create a project and page
    project = Project(name="Test Project")
    page = Page()
    project.add_page(page)

    # Create a template manager with the project
    template_manager = TemplateManager(project=project)

    # Create a template (not embedded yet)
    template = Template(name="Auto Embed Test", description="Should auto-embed")
    placeholder = PlaceholderData(placeholder_type="image", x=10, y=10, width=100, height=100)
    template.add_element(placeholder)

    # Apply template with auto_embed=True (default)
    template_manager.apply_template_to_page(template, page)

    # Verify template was auto-embedded
    assert "Auto Embed Test" in project.embedded_templates


def test_auto_embed_on_create_page():
    """Test that templates are automatically embedded when creating pages"""
    # Create a project
    project = Project(name="Test Project")

    # Create a template manager with the project
    template_manager = TemplateManager(project=project)

    # Create a template (not embedded yet)
    template = Template(name="Auto Embed Page Test", description="Should auto-embed")
    placeholder = PlaceholderData(placeholder_type="image", x=10, y=10, width=100, height=100)
    template.add_element(placeholder)

    # Create page from template with auto_embed=True (default)
    page = template_manager.create_page_from_template(template, page_number=1)

    # Verify template was auto-embedded
    assert "Auto Embed Page Test" in project.embedded_templates


def test_delete_embedded_template():
    """Test deleting an embedded template"""
    # Create a project
    project = Project(name="Test Project")

    # Create a template manager with the project
    template_manager = TemplateManager(project=project)

    # Embed a template
    template = Template(name="To Delete")
    template_manager.embed_template(template)

    assert "To Delete" in project.embedded_templates

    # Delete the embedded template
    template_manager.delete_template("[Embedded] To Delete")

    assert "To Delete" not in project.embedded_templates


def test_embedded_template_with_text():
    """Test embedding template with text elements"""
    # Create a project
    project = Project(name="Test Project")

    # Create a template manager with the project
    template_manager = TemplateManager(project=project)

    # Create a template with text
    template = Template(name="Text Template")
    textbox = TextBoxData(text_content="Sample Text", x=10, y=10, width=200, height=50)
    template.add_element(textbox)

    # Embed and reload
    template_manager.embed_template(template)
    loaded = template_manager.load_template("Text Template")

    assert len(loaded.elements) == 1
    assert isinstance(loaded.elements[0], TextBoxData)
    assert loaded.elements[0].text_content == "Sample Text"


def test_roundtrip_serialization():
    """Test complete roundtrip: create project, embed template, serialize, deserialize"""
    # Create a project with pages and embedded template
    project = Project(name="Roundtrip Test")
    template_manager = TemplateManager(project=project)

    # Create a template
    template = Template(name="Roundtrip Template", page_size_mm=(200, 300))
    placeholder1 = PlaceholderData(placeholder_type="image", x=10, y=10, width=80, height=80)
    placeholder2 = PlaceholderData(placeholder_type="image", x=110, y=10, width=80, height=80)
    template.add_element(placeholder1)
    template.add_element(placeholder2)

    # Create a page from this template
    page = template_manager.create_page_from_template(template, page_number=1)
    project.add_page(page)

    # Serialize
    serialized = project.serialize()

    # Create new project and deserialize
    new_project = Project(name="New Roundtrip")
    new_project.deserialize(serialized)

    # Verify embedded template
    assert "Roundtrip Template" in new_project.embedded_templates

    # Verify we can use the template
    new_template_manager = TemplateManager(project=new_project)
    loaded_template = new_template_manager.load_template("Roundtrip Template")

    assert loaded_template.name == "Roundtrip Template"
    assert loaded_template.page_size_mm == (200, 300)
    assert len(loaded_template.elements) == 2

    # Create another page from the loaded template
    new_page = new_template_manager.create_page_from_template(
        loaded_template, page_number=2, auto_embed=False  # Don't embed again
    )
    assert len(new_page.layout.elements) == 2
