#!/usr/bin/freecadcmd

import os
import FreeCAD as App  # type: ignore
import FreeCADGui as Gui  # type: ignore

# Define the project root directory
project_root = os.path.abspath(
    os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir)
)

# Define the CAD directory
cad_dir = os.path.join(project_root, "cad")

# Define the output directory
output_dir = os.path.join(project_root, "tex", "images", "2_prakticka_cast")

# Ensure the output directory exists
os.makedirs(output_dir, exist_ok=True)

# Iterate over all files in the CAD directory (excluding nested directories)
for file in os.listdir(cad_dir):
    if file.endswith(".FCStd"):
        file_path = os.path.join(cad_dir, file)
        App.Console.PrintMessage(f"\nProcessing {file_path}\n")

        # Open the FreeCAD document
        doc = App.open(file_path)
        App.setActiveDocument(doc.Name)
        App.ActiveDocument.recompute()

        # Check if the document contains any assemblies (App::Part)
        has_assembly = any(
            hasattr(obj, "Type") and obj.Type == "Assembly" for obj in doc.Objects
        )

        if has_assembly:
            # Gui.showMainWindow()

            # Set visibility to true for all objects in the assembly and hide all objects outside of the assembly
            for obj in doc.Objects:
                if hasattr(obj, "Type") and obj.Type == "Assembly":
                    for sub_obj in obj.OutList:
                        if sub_obj.ViewObject is not None:
                            sub_obj.ViewObject.Visibility = True
                else:
                    if obj.ViewObject is not None:
                        obj.ViewObject.Visibility = False

            for view in [
                "ViewIsometric",
                "ViewFront",
                "ViewTop",
                "ViewRight",
                "ViewRear",
                "ViewBottom",
                "ViewLeft",
            ]:
                Gui.ActiveDocument.sendMsgToViews(view)
                output_path = os.path.join(
                    output_dir, f'{file.replace(".FCStd", "")}_{view}.png'
                )
                Gui.ActiveDocument.ActiveView.saveImage(
                    output_path, 1920, 1080, "Transparent"
                )
                App.Console.PrintMessage(f"Exported {view} view to {output_path}\n")

        else:
            App.Console.PrintMessage(
                f"No assembly found in {file_path}, skipping image generation.\n"
            )

        # Close the FreeCAD document
        App.closeDocument(doc.Name)
