using FeMM.Grasshopper.Helpers;
using Grasshopper.Kernel;
using St7API;
using System;
using System.Collections.Generic;

namespace FeMM.Grasshopper.Components.ST2R
{
    public class St7CloseModelComponent : GH_Component
    {
        private bool _run = false;

        public St7CloseModelComponent()
            : base("Close Straus7 Model", "CloseModel",
                  "Closes an open Straus7 model and deletes any scratch files",
                  CategoryNameConstants.CATEGORY_F2R, CategoryNameConstants.SUBCATEGORY_ST2R_BAKE)
        {
        }

        public override void CreateAttributes()
        {
            var buttonAttributes = new ComponentAttributes.ComponentOneButtonAttributes(this, "Close");
            buttonAttributes.ButtonPressed += () =>
            {
                _run = true;
                ExpireSolution(true);
            };
            m_attributes = buttonAttributes;
        }

        protected override void RegisterInputParams(GH_InputParamManager p)
        {
            p.AddIntegerParameter("uID", "ID", "Straus7 model ID (must be already opened)", GH_ParamAccess.item);
        }

        protected override void RegisterOutputParams(GH_OutputParamManager p)
        {
            p.AddTextParameter("Log", "Log", "Debug log messages", GH_ParamAccess.list);
        }

        protected override void SolveInstance(IGH_DataAccess DA)
        {
            int uID = 0;
            if (!DA.GetData(0, ref uID)) return;

            List<string> log = [];

            if (!_run)
            {
                DA.SetDataList(0, log);
                return;
            }

            log.Add($"Closing Straus7 model with uID = {uID}...");

            int err = St7.St7CloseFile(uID);

            if (err == St7.ERR7_NoError)
            {
                log.Add("Model closed successfully.");
            }
            else if (err == 12)
            {
                log.Add("Error: Straus7 model is not open or uID is invalid.");
            }
            else
            {
                log.Add($"Error closing model: {err}");
            }

            DA.SetDataList(0, log);
            _run = false;
        }

        protected override System.Drawing.Bitmap Icon => Properties.Resources.St7CloseModelIcon;

        public override Guid ComponentGuid =>
            new("a1b2c3d4-5678-4f9a-9012-abcdef123456");
    }
}
303 files24 directories