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

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

        public St7ReadLimitEnvelopeNamesComponent()
            : base("Read Limit Envelope Names", "ReadLimitEnvNames",
                  "Reads the names of limit envelopes from the result file",
                  CategoryNameConstants.CATEGORY_F2R, CategoryNameConstants.SUBCATEGORY_ST2R_BAKE)
        {
        }

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

        protected override void RegisterInputParams(GH_InputParamManager p)
        {
            p.AddIntegerParameter("uID", "ID", "uID of the already opened Straus7 model", GH_ParamAccess.item);
            p.AddTextParameter("Result File", "Res", "Path to the .RST / .NLA / .NLF result file", GH_ParamAccess.item);
        }

        protected override void RegisterOutputParams(GH_OutputParamManager p)
        {
            p.AddTextParameter("Limit Envelope Names", "Names", "Names of limit envelopes", GH_ParamAccess.list);
            p.AddTextParameter("Log", "Log", "Debug log messages", GH_ParamAccess.list);
        }

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

            List<string> envelopeNames = [];
            List<string> log = [];

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

            log.Add($"Opening result file: {resultFile}");
            int numPrimary = 0, numSecondary = 0;
            int err = St7.St7OpenResultFile(uID, resultFile, null, St7.kNoCombinations, ref numPrimary, ref numSecondary);

            if (err != St7.ERR7_NoError)
            {
                log.Add($"Error opening result file (code {err})");
                DA.SetDataList(0, envelopeNames);
                DA.SetDataList(1, log);
                _run = false;
                return;
            }

            log.Add($"Result file opened. Primary={numPrimary}, Secondary={numSecondary}");

            // Get number of envelopes
            int numLimit = 0, numComb = 0, numFactor = 0;
            err = St7.St7GetNumEnvelopes(uID, ref numLimit, ref numComb, ref numFactor);
            if (err != St7.ERR7_NoError)
            {
                log.Add($"Error getting envelope counts (code {err})");
                DA.SetDataList(0, envelopeNames);
                DA.SetDataList(1, log);
                _run = false;
                return;
            }

            log.Add($"Envelope counts: Limit={numLimit}, Combination={numComb}, Factor={numFactor}");

            // Iterate limit envelopes
            for (int i = 1; i <= numLimit; i++)
            {
                StringBuilder name = new(256);
                int envType = 0;
                err = St7.St7GetLimitEnvelopeData(uID, i, ref envType, name, name.Capacity);
                if (err != St7.ERR7_NoError)
                {
                    log.Add($"Error reading limit envelope {i} (code {err})");
                    continue;
                }

                envelopeNames.Add(name.ToString().TrimEnd('\0'));
                log.Add($"Found limit envelope {i}: {name} (Type={envType})");
            }

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

        protected override System.Drawing.Bitmap Icon => Properties.Resources.St7ReadLimitEnvelopeNamesIcon;
        public override Guid ComponentGuid => new("6a2e5f4b-1f23-4bfa-b2d0-123456789abc");
    }
}
303 files24 directories