using SAP2000v1;
using FeMM.Grasshopper.DataTypes;
using FeMM.Grasshopper.DataTypes.FeMM;
using FeMM.Grasshopper.Helpers;
using Grasshopper.Kernel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Versioning;

namespace FeMM.Grasshopper.Components.Export
{
#if NETCOREAPP
    [SupportedOSPlatform("windows")]
#endif
    public class SapExportComponent : GH_Component
    {
        protected string _status;
        protected bool _run;

        /// <summary>
        /// Initializes a new instance of the SapExportComponent class.
        /// </summary>
        public SapExportComponent()
          : base("SAP2000 Export", "SDB", "Export to SAP2000", CategoryNameConstants.CATEGORY_FEMM, CategoryNameConstants.SUBCATEGORY_EXPORT)
        {
            _status = "";
            _run = false;
        }

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

        /// <summary>
        /// Registers all the input parameters for this component.
        /// </summary>
        protected override void RegisterInputParams(GH_InputParamManager pManager)
        {
            pManager.AddGenericParameter("Model", "M", "The FEM model", GH_ParamAccess.item);
            pManager.AddGenericParameter("Design Prefs", "DP", "Design preferences", GH_ParamAccess.list);
            pManager[1].Optional = true;
            pManager.AddTextParameter("Output Path", "O", "The full path of the file model to create", GH_ParamAccess.item, "");
            pManager[2].Optional = true;
            pManager.AddBooleanParameter("Attach", "A", "Attach to the active instance (if exists)", GH_ParamAccess.item, false);
            pManager[3].Optional = true;
            pManager.AddTextParameter("SAP Path", "P", "The path of the main SAP2000 executable", GH_ParamAccess.item, "");
            pManager[4].Optional = true;
            pManager.AddBooleanParameter("Keep Model Open", "K", "Keep Model Open", GH_ParamAccess.item, true);
        }

        /// <summary>
        /// Registers all the output parameters for this component.
        /// </summary>
        protected override void RegisterOutputParams(GH_OutputParamManager pManager)
        {
            pManager.AddGenericParameter("Status", "S", "The status of the export", GH_ParamAccess.item);
        }

        /// <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)
        {
            Message = "";
            GH_Model model = null;
            string outputPath = "";
            bool attachToInstance = false;
            string programPath = "";
            bool keepSAPOpen = true;

            if (!DA.GetData("Model", ref model))
                return;
            DA.GetData("Output Path", ref outputPath);
            DA.GetData("Attach", ref attachToInstance);                
            DA.GetData("SAP Path", ref programPath);
            DA.GetData("Keep Model Open", ref keepSAPOpen);

            if(!attachToInstance && string.IsNullOrWhiteSpace(outputPath))
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "No file path or attach to istance option");
                return;
            }
            if (!attachToInstance)
            {
                if (Path.GetExtension(outputPath).ToLower() != ".sdb")
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Invalid extension in file name");
                    return;
                }
            }

            var prefs = new List<GH_SteelPrefs>(); // Actually only steel. For future also rc,alum,ecc
            Common.Checks.SteelPrefs spref = null;
            if (DA.GetDataList("Design Prefs", prefs))
            {
                if (prefs.Count == 1)
                {
                    spref = prefs[0].Value;
                }
                else
                {
                    return;
                }
            }

            if (_run)
            {
#if !DEBUG
                try
                {

                }
                catch (Exception){}
#endif

                try
                {
                    cOAPI sapObject = null;
                    try
                    {
                        sapObject = Common.Helpers.SapHelper.GetSapObject(attachToInstance, "", programPath);
                    }
                    catch (Exception ex)
                    {
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Error, ex.Message);
                        return;
                    }

                    try
                    {
                        if (Common.Helpers.SapHelper.CreateModel(sapObject, attachToInstance, model.Value, Rhino.Settings.Tolerance,
                            out cSapModel sapModel, out List<string> warnings, out List<string> errors, spref))
                        {
                            sapModel.View.RefreshView(0, false);
                            sapModel.File.Save(outputPath);

                            if (keepSAPOpen == false)                            
                                sapObject.ApplicationExit(true);
                            
                            Message = "Done";
                        }
                        else
                        {
                            Message = "Failed";
                        }
                        foreach (string error in errors)
                            AddRuntimeMessage(GH_RuntimeMessageLevel.Error, error);
                        foreach (string warning in warnings)
                            AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, warning);
                    }
                    catch (Exception e)
                    {
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Error, e.Message);
                        Message = "Error";
                        sapObject.ApplicationExit(false);
                        sapObject = null;
                    }
                }
                finally
                {
                    _run = false;
                }
            }

            _status = Message;

            DA.SetData(0, _status);
        }

        /// <summary>
        /// Provides an Icon for the component.
        /// </summary>
        protected override System.Drawing.Bitmap Icon => Properties.Resources.SapExportIcon;

        /// <summary>
        /// Gets the unique ID for this component. Do not change this ID after release.
        /// </summary>
        public override Guid ComponentGuid => new("908daf1d-67c7-4808-a699-97e574f14a53");
    }
}
303 files24 directories