using FeMM.Common.Models;
using FeMM.Grasshopper.DataTypes.FeMM;
using FeMM.Grasshopper.Helpers;
using Grasshopper.Kernel;
using Grasshopper.Kernel.Special;
using MeChecksApi;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Versioning;

namespace FeMM.Grasshopper.Components.MeCheck
{
#if NETCOREAPP
    [SupportedOSPlatform("windows")]
#endif
    public class MixedSectionBeamCheckComponent : GH_Component
    {
        /// <summary>
        /// Initializes a new instance of the MixedSectionBeamCheckComponent class.
        /// </summary>
        public MixedSectionBeamCheckComponent()
          : base("Mixed Section Beam Check", "MSBC", "Perform the security chech of a super-beam with mixed sections", CategoryNameConstants.CATEGORY_CHECKS, CategoryNameConstants.SUBCATEGORY_MECHECK)
        {
        }

        /// <summary>
        /// Registers all the input parameters for this component.
        /// </summary>
        protected override void RegisterInputParams(GH_InputParamManager pManager)
        {
            pManager.AddGenericParameter("Model", "M", "The FEM model from MeChecks", GH_ParamAccess.item);
            pManager.AddGenericParameter("Beams", "B", "The model beams definitions", GH_ParamAccess.list);
            pManager.AddTextParameter("Phase Inf Load Cases", "INF", "The load cases name to assign to the Inf phase", GH_ParamAccess.list);
            pManager[2].Optional = true;
            pManager.AddTextParameter("Phase Ninf Load Cases", "NINF", "The load cases name to assign to the NInf phase", GH_ParamAccess.list);
            pManager[3].Optional = true;
            pManager.AddTextParameter("Phase N0 Load Cases", "N0", "The load cases name to assign to the N0 phase", GH_ParamAccess.list);
            pManager[4].Optional = true;
            /*
            pManager.AddNumberParameter(char.ConvertFromUtf32(0x3B3) + "s", char.ConvertFromUtf32(0x3B3) + "s", "Partial safety factor of rebar", GH_ParamAccess.item, 1.15);
            pManager.AddNumberParameter(char.ConvertFromUtf32(0x3B3) + "c", char.ConvertFromUtf32(0x3B3) + "c", "Partial safety factor of concrete", GH_ParamAccess.item, 1.5);
            pManager.AddNumberParameter(char.ConvertFromUtf32(0x3B1) + "cc", char.ConvertFromUtf32(0x3B1) + "cc", char.ConvertFromUtf32(0x3B1) + "cc factor of concrete", GH_ParamAccess.item, 0.85);
            pManager.AddNumberParameter(char.ConvertFromUtf32(0x3B3) + "m0", char.ConvertFromUtf32(0x3B3) + "m0", "Partial safety factor of rebar", GH_ParamAccess.item, 1.05);
            */
            pManager.AddNumberParameter("Concrete design stress", "CS", "Concrete design stress", GH_ParamAccess.item);
            pManager.AddNumberParameter("Web yield stress", "WS", "Steel design yield stress of web carpenty", GH_ParamAccess.item);
            pManager.AddNumberParameter("Rebar yiend stress", "RS", "Design yield stress of reinforcement steel", GH_ParamAccess.item);
            pManager.AddNumberParameter("Short-life homogenization", "SH", "Short-life load homogenization coefficient", GH_ParamAccess.item);
            pManager.AddNumberParameter("Long-life homogenization", "LH", "Long-life load homogenization coefficient", GH_ParamAccess.item);
            pManager.AddNumberParameter("Slenderness", "SP", "Slenderness reduction parameter", GH_ParamAccess.item);
        }

        /// <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)
        {
            GH_Model model = null;
            var beams = new List<GH_MixedSectionBeam>();
            double fcd = 0, fyd = 0, fydar = 0, n0 = 0, n1 = 0, c235 = 0;
            var lcs_inf = new List<string>();
            var lcs_ninf = new List<string>();
            var lcs_n0 = new List<string>();

            int n = 0;
            if (!DA.GetData(n++, ref model))
                return;
            if (!DA.GetDataList(n++, beams))
                return;
            if (!DA.GetDataList(n++, lcs_inf))
                AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Input parameter Inf failed to collect data");
            if (!DA.GetDataList(n++, lcs_ninf))
                AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Input parameter Ninf failed to collect data");
            if (!DA.GetDataList(n++, lcs_n0))
                AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Input parameter N0 failed to collect data");
            if (!DA.GetData(n++, ref fcd))
                return;
            if (!DA.GetData(n++, ref fyd))
                return;
            if (!DA.GetData(n++, ref fydar))
                return;
            if (!DA.GetData(n++, ref n0))
                return;
            if (!DA.GetData(n++, ref n1))
                return;
            if (!DA.GetData(n++, ref c235))
                return;

            if (!model.IsValid)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Model not valid");
                return;
            }
            if (beams.Count == 0)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Empty beams definition list");
                return;
            }
            if (beams.Count != model.Value.Beams.Count())
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "The number of beams doesn't match the number of beams");
                return;
            }

            if (((GH_Attributes<IGH_Component>)Params.Input[0].Sources[0].Attributes.GetTopLevel).Owner is SuperElementCheckComponent se)
            {
                // Connect the ValueList component on the phases input item
                for (int p = 2; p <= 4; p++)
                {
                    IEnumerable<IGH_Param> keys_analysisResultLists = Params.Input[p].Sources
                        .Where(s => s.GetType() == typeof(GH_ValueList));
                    foreach (GH_ValueList vallist in keys_analysisResultLists)
                    {
                        if (vallist.ListMode != GH_ValueListMode.CheckList)
                            vallist.ListMode = GH_ValueListMode.CheckList;
                        ComponentsHelper.SetValueList(vallist, se.CasesNames);
                        vallist.NickName = Params.Input[p].NickName;
                    }
                }

                if (se.IsRunning)
                {
                    IMeChecksApi api = ApiHelper.Connect();
                    if (api == null)
                    {
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Unable to connect with meChecks. Please check in the program is running");
                        return;
                    }

                    api.AddCheckModule("MixSecsBeamSecCheck");

                    api.CallPluginApi("MixSecsBeamSecCheck", "SetPhaseLoadCases", "Inf", lcs_inf.ToArray());
                    api.CallPluginApi("MixSecsBeamSecCheck", "SetPhaseLoadCases", "Ninf", lcs_ninf.ToArray());
                    api.CallPluginApi("MixSecsBeamSecCheck", "SetPhaseLoadCases", "N0", lcs_n0.ToArray());

                    foreach (BeamModel beam_model in model.Value.Beams)
                    {
                        GH_MixedSectionBeam beam = beams.SingleOrDefault(b => b.Beam.Value.BeamId == beam_model.BeamId);
                        if (beam == null)
                        {
                            AddRuntimeMessage(GH_RuntimeMessageLevel.Error, $"Cannot find the beam {beam_model.BeamId}");
                            return;
                        }

                        api.CallPluginApi("MixSecsBeamSecCheck", "SetFrameSection", beam.Beam.Value.BeamId, beam.StartSection.Name,
                        beam.StartSection.ConcreteSection.B, beam.StartSection.ConcreteSection.D,
                        beam.StartSection.ReinforcementCover, beam.StartSection.ReinforcementArea,
                        beam.StartSection.SteelSection.B2, beam.StartSection.SteelSection.T2, beam.StartSection.SteelSection.T3,
                        beam.StartSection.SteelSection.D, beam.StartSection.SteelSection.B1, beam.StartSection.SteelSection.T1,
                        fcd, fyd, fydar, n0, n1, c235, beam.EndSection.Name, beam.EndSection.ConcreteSection.B,
                        beam.EndSection.ConcreteSection.D, beam.EndSection.ReinforcementCover, beam.EndSection.ReinforcementArea,
                        beam.EndSection.SteelSection.B2, beam.EndSection.SteelSection.T2, beam.EndSection.SteelSection.T3,
                        beam.EndSection.SteelSection.D, beam.EndSection.SteelSection.B1, beam.EndSection.SteelSection.T1, fcd,
                        fyd, fydar, n0, n1, c235);
                    }

                    api.CallPluginApi("MixSecsBeamSecCheck", "Check");

                    api.UpdateUI();
                    api.SaveJob();

                    se.IsRunning = false;
                }
            }
            else
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "This component must be connected only to the 'Super Element Check' component");
                return;
            }
        }

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

        /// <summary>
        /// Gets the unique ID for this component. Do not change this ID after release.
        /// </summary>
        public override Guid ComponentGuid => new("c903d16a-6b6d-47ea-bf19-663dfb88f1ac");
    }
}
303 files24 directories