using SAP2000v1;
using FeMM.Grasshopper.Helpers;
using Grasshopper.Kernel;
using Grasshopper.Kernel.Types;
using Rhino;
using Rhino.DocObjects;
using System;
using System.Collections.Generic;
using System.Runtime.Versioning;

namespace FeMM.Grasshopper.Components.F2R
{
#if NETCOREAPP
    [SupportedOSPlatform("windows")]
#endif
    public class SAPSplitBeamComponent : GH_Component
    {
        private bool _run = false;

        /// <summary>
        /// Initializes a new instance of the MyComponent1 class.
        /// </summary>
        public SAPSplitBeamComponent()
            : base("Split F2R Beam", "SB", "Split the selected beams in SAP2000", CategoryNameConstants.CATEGORY_F2R, CategoryNameConstants.SUBCATEGORY_F2R_INTERACTIVESAP)
        {
        }

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

            m_attributes = buttonAttributes;
        }

        /// <summary>
        /// Registers all the input parameters for this component.
        /// </summary>
        protected override void RegisterInputParams(GH_InputParamManager pManager)
        {
            pManager.AddTextParameter("Model Path", "MP", "Sap2000 model path to open. If empty it will open an empty file", GH_ParamAccess.item, "");
            pManager[0].Optional = true;
            pManager.AddBooleanParameter("Attach to Instance", "AI", "Attach to instance. If true, 'model path' will be ignored", GH_ParamAccess.item, false);
            pManager[1].Optional = true;
            pManager.AddGeometryParameter("Beams", "B", "F2R curve to split", GH_ParamAccess.list);
            pManager.AddGeometryParameter("Splitters", "S", "F2R element used for split", GH_ParamAccess.list);
        }

        /// <summary>
        /// Registers all the output parameters for this component.
        /// </summary>
        protected override void RegisterOutputParams(GH_OutputParamManager pManager)
        {

        }

        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            string modelPath = "";
            bool attachToInstance = false;
            var elements = new List<IGH_GeometricGoo>();
            var splitters = new List<IGH_GeometricGoo>();

            //input
            DA.GetData(0, ref modelPath);
            DA.GetData(1, ref attachToInstance);
            if (!DA.GetDataList(2, elements))
                return;
            if (!DA.GetDataList(3, splitters))
                return;

            if (_run)
            {
                if (!System.IO.File.Exists(modelPath) && !attachToInstance) // model path non valido, Se path modello non valido fa partire con stringa vuota (file vuoto)
                {
                    modelPath = string.Empty;
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Sap model path not valid, opening an empty file");
                    _run = false;
                }
                if (elements.Count == 0)
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "No elements selected");
                    _run = false;
                }
                if (splitters.Count == 0)
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "No splitters selected");
                    _run = false;
                }
                try
                {
                    cSapModel sapModel = F2RModelHelper.GetSapModel(out cOAPI sapObject, modelPath, attachToInstance);

                    sapModel.SelectObj.ClearSelection();

                    string groupNameCustom = (DateTime.Now.Hour + DateTime.Now.Minute + DateTime.Now.Second + DateTime.Now.Millisecond + DateTime.Now.Ticks).ToString();
                    sapModel.GroupDef.SetGroup(groupNameCustom);

                    RhinoDoc doc = RhinoDoc.ActiveDoc;

                    for (int i = 0; i < splitters.Count; i++)
                    {
                        Guid guid = splitters[i].ReferenceID;
                        if (guid != Guid.Empty)
                        {
                            RhinoObject rhinoObj = doc.Objects.FindId(guid);

                            if (rhinoObj != null)
                            {
                                string id = rhinoObj.Attributes.GetUserString("F2R_ID");
                                if (rhinoObj.GetType() == typeof(PointObject))
                                {
                                    sapModel.PointObj.SetGroupAssign(id, groupNameCustom, false);
                                }
                                else if (rhinoObj.GetType() == typeof(CurveObject))
                                {
                                    sapModel.FrameObj.SetGroupAssign(id, groupNameCustom, false);
                                }
                                else if (rhinoObj.GetType() == typeof(SurfaceObject) || rhinoObj.GetType() == typeof(BrepObject))
                                {
                                    sapModel.AreaObj.SetGroupAssign(id, groupNameCustom, false);
                                }
                                else
                                {
                                    AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, $"Element n° {i} is not a point or a curve or a surface");
                                }
                            }
                            else
                            {
                                AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, $"Element n° {i} don't exist in Rhino");
                            }
                        }
                        else
                        {
                            AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, $"Element {i} don't have a valid GUID");
                        }
                    }

                    var elemToSplitId = new List<string>();
                    for (int i = 0; i < elements.Count; i++)
                    {
                        Guid guid = elements[i].ReferenceID;
                        if (guid != Guid.Empty)
                        {
                            RhinoObject rhinoObj = doc.Objects.FindId(guid);

                            if (rhinoObj != null)
                            {
                                string id = rhinoObj.Attributes.GetUserString("F2R_ID");
                                if (rhinoObj.GetType() == typeof(CurveObject))
                                {
                                    elemToSplitId.Add(id);
                                }
                                else
                                {
                                    AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, $"Element n° {i} with ID: {id} is not a curve");
                                }
                            }
                            else
                            {
                                AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, $"Element n° {i} don't exist in Rhino");
                            }
                        }
                        else
                        {
                            AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, $"Element {i} don't have a valid GUID");
                        }
                    }

                    for (int i = 0; i < elemToSplitId.Count; i++)
                    {
                        string id = elemToSplitId[i];
                        sapModel.SelectObj.Group(groupNameCustom, false);

                        int numb = 0;
                        string[] newName = [];
                        if (sapModel.EditFrame.DivideAtIntersections(id, ref numb, ref newName) == 0)
                        {
                            if (numb > 0)
                            {
                                for (int j = 0; j < newName.Length; j++)
                                {
                                    string name = id + "-" + (j + 1);
                                    sapModel.FrameObj.ChangeName(newName[j], name);
                                }
                            }
                        }
                        else
                        {
                            AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, $"Impossible to divide element n° {i} with ID: {id}");
                        }
                    }

                    sapModel.GroupDef.Clear(groupNameCustom);
                    sapModel.GroupDef.Delete(groupNameCustom);

                    if (attachToInstance)
                        sapModel.View.RefreshView();

                    if (!attachToInstance)
                        sapObject.ApplicationExit(true);

                    _run = false;
                }
                catch (Exception)
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Generic error");
                    _run = false;
                }
            }
        }

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

        public override Guid ComponentGuid => new("9d3a3bf4-6c9c-4b00-8d98-dad51634b9a8");
    }
}
303 files24 directories