import streamlit as st
import pyvista as pv
import tempfile
from stpyvista import stpyvista
import os

def delmodel():
    del st.session_state.fileuploader

def option_stl_1():
    """📤 Upload a STL file"""

    st.header("📤   Upload a x3D STL file", anchor=False, divider="rainbow")

    placeholder = st.empty()
    " "

    with placeholder:
        uploadedFile = st.file_uploader(
            "Upload a x3D file:",
            ["stl"],
            accept_multiple_files=False,
            key="fileuploader",
        )

    if uploadedFile:
        st.info(f"Uploaded file size: {uploadedFile.size} bytes")

        # Save to temporary file
        with tempfile.NamedTemporaryFile(suffix=".stl", delete=False) as f:
            f.write(uploadedFile.getbuffer())
            f.flush()
            temp_file_path = f.name

        try:
            reader = pv.STLReader(temp_file_path)
            mesh = reader.read()

            st.info(f"Mesh points: {mesh.n_points}, Mesh cells: {mesh.n_cells}")

            if mesh.n_points == 0:
                st.error("The uploaded STL file is empty or invalid. Please upload a valid file.")
            else:
                plotter = pv.Plotter(border=False, window_size=[500, 400])
                plotter.background_color = "#f0f8ff"
                plotter.add_mesh(mesh, color="orange", specular=0.5)
                plotter.view_xz()

                with placeholder.container():
                    st.button("🔙 Restart", "btn_rerender", on_click=delmodel)
                    stpyvista(plotter)
        finally:
            os.remove(temp_file_path)  # Clean up the temp file

def option_stl_2(file_path):
    st.header("📤   Using embed exported file x3D", anchor=False, divider="rainbow")
    placeholder = st.empty()
    " "
    if file_path:
        if os.path.exists(file_path) and file_path.endswith(".stl"):
            try:
                reader = pv.STLReader(file_path)
                mesh = reader.read()

                st.info(f"Mesh points: {mesh.n_points}, Mesh cells: {mesh.n_cells}")

                if mesh.n_points == 0:
                    st.error("The uploaded STL file is empty or invalid. Please upload a valid file.")
                else:
                    plotter = pv.Plotter(border=False, window_size=[500, 400])
                    plotter.background_color = "#f0f8ff"
                    plotter.add_mesh(mesh, color="orange", specular=0.5)
                    plotter.view_xz()

                    with placeholder.container():
                        st.button("🔙 Restart", "btn_rerender")
                        stpyvista(plotter)
            finally:
                st.info("Processing completed.")
        else:
            st.error("Invalid file path. Please ensure the file exists and is an STL file.")