using RnD.API;
using RnD.Attributes;
using RnD.Model;
using System.Linq;

namespace TransferringLocationToAttribute
{
    [CustomFunction("TransferringLocationToAttributeCustomAction", RnD.Common.Enums.CustomFunctionType.CustomAction)]
    public class TransferringLocationToAttributeCustomAction : AdvancedCustomFunction, ICustomAction<ICustomContext>
    {
        #region Constructors
        public TransferringLocationToAttributeCustomAction(IAPI aAPI) : base(aAPI)
        {
        }
        #endregion

        #region Methods
        public void Execute(ICustomContext aContext)
        {
            var entity = aContext.Entity;

            if (entity is null)
            {
                Log.Error("entity was null");
                return;
            }

            if (!(entity is ISample sample))
            {
                Log.Error("Entity is not sample");
                return;
            }

            var locationId = DatabaseContext.RndvScLo.FirstOrDefault(c => c.SC == sample.ID).LO;
            var locationName = DatabaseContext.RndvLoLang.FirstOrDefault(c => c.LO == locationId).DESCRIPTION;
            var locationAttribute = DatabaseContext.RndvAu.Where(c => c.AU == 53).OrderByDescending(c => c.VERSION).FirstOrDefault(); // 53 - Id required attribute

            if (locationAttribute == null)
            {
                Log.Error("Location attribute not found");
                return;
            }

            var foundedScAu = DatabaseContext.RndvScAu.FirstOrDefault(c => c.AU == locationAttribute.AU && c.SC == sample.ID);
            if (foundedScAu == null)
            {
                DatabaseContext.RndvScAu.Add(new RnD.Model.EF.RndvScAu
                {
                    SC = (decimal)sample.ID,
                    AU = locationAttribute.AU,
                    AU_VERSION = locationAttribute.VERSION,
                    AUSEQ = locationAttribute.TR_SEQ,
                    VALUE = locationName
                });
            }
            else
            {
                foundedScAu.VALUE = locationName;
            }

            DatabaseContext.SaveChanges();
        }
        #endregion
    }
}
