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

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

        public St7CloseResultFileComponent()
            : base("Close Straus7 Result File", "CloseResultFile",
                  "Closes any open result file for a given Straus7 model",
                  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", 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($"Attempting to close result file for model uID = {uID}...");

            int err = St7.St7CloseResultFile(uID);

            switch (err)
            {
                case St7.ERR7_NoError:
                    log.Add("Result file closed successfully.");
                    break;
                case 12: // No result file open
                    log.Add("No result file is currently open for this model.");
                    break;
                default:
                    log.Add($"Error closing result file: {err}");
                    break;
            }

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

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

        public override Guid ComponentGuid =>
            new("9f1a2b3c-4d5e-678f-9012-abcdef123456");
    }
}
303 files24 directories