using EgtBEAMWALL.DataLayer.DatabaseModels;
using NLog;
using System;
using System.Collections.Generic;
using System.Linq;

namespace EgtBEAMWALL.DataLayer.Controllers
{
    public class MachGroupController : IDisposable
    {
        #region Public Constructors

        public MachGroupController()
        {
        }

        #endregion Public Constructors

        #region Public Methods

        /// <summary>
        /// Conversion of base class to DB model class
        /// </summary>
        /// <param name="coreMachGroup"></param>
        /// <param name="currProdDbId"></param>
        /// <returns></returns>
        public MachGroupModel ConvertFromCore(Core.MyMachGroupM coreMachGroup, int currProdDbId)
        {
            MachGroupModel answ = new MachGroupModel();
            if (coreMachGroup != null)
            {
                answ = new MachGroupModel()
                {
                    SupervisorId = "",
                    Name = coreMachGroup.Name,
                    Locked = true,
                    MachGroupId = coreMachGroup.Id,
                    ProdDbId = currProdDbId,
                    State = Core.ItemState.ND,
                    H = coreMachGroup.dH,
                    L = coreMachGroup.dL,
                    W = coreMachGroup.dW,
                    DtStart = coreMachGroup.dtStartTime,
                    DtEnd = coreMachGroup.dtEndTime,
                    Material = coreMachGroup.sMATERIAL,
                    // indice ordinale SOLO SE è >= 0
                    ProdIndex = coreMachGroup.nProdIndex >= 0 ? coreMachGroup.nProdIndex : 10000
                };
            }
            return answ;
        }

        /// <summary> Add MachGroup as rebuilt from NeedRedo (on top of order priority) <param
        /// name="ProdId">Id del Prod</param> <param name="newMachGroup">Nuovo MachGroup da
        /// associare</param> <returns></returns>
        public ProdModel AddMachGroupRedo(int ProdId, Core.MyMachGroupM newMachGroup)
        {
            ProdModel currData = new ProdModel();
            List<PartModel> PartList2Add = new List<PartModel>();
            var myPartCtrl = new PartController();
            var myStatusMapCtrl = new StatusMapController();
            using (DatabaseContext localDbCtx = new DatabaseContext(DbConfig.CONNECTION_STRING))
            {
                // Recupero il PROD nel contesto
                currData = localDbCtx
                                        .ProdList
                                        .Where(x => x.ProdId == ProdId)
                                        .SingleOrDefault();
                try
                {
                    var locMGCtrl = new MachGroupController();
                    var convCurrMG = locMGCtrl.ConvertFromCore(newMachGroup, currData.ProdDbId);

                    convCurrMG.ProdIndex = 1;

                    // aggiungo MachGroup
                    localDbCtx.MachGroupList.Add(convCurrMG);
                    // Commit changes
                    localDbCtx.SaveChanges();

                    int MachGroupDbId = FindByMachGroupId(ProdId, newMachGroup.Id).MachGroupDbId;
                    // 2023.05.10 leggo elenco part in una sola volta

                    var currMgPartList = localDbCtx
                                      .PartList
                                      .Where(x => x.MachGroup.Prod.ProdId == ProdId && x.MachGroup.MachGroupId == newMachGroup.Id)
                                      .ToList();
                    // verifico se uguali o meno...
                    foreach (var currPartM in newMachGroup.PartMList)
                    {
                        //var currPart = localDbCtx
                        //                  .PartList
                        //                  .Where(x => x.MachGroup.Prod.ProdId == ProdId && x.MachGroup.MachGroupId == newMachGroup.Id && x.PartId == currPartM.nPartId)
                        //                  .SingleOrDefault();
                        var currPart = currMgPartList
                                          .Where(x => x.PartId == currPartM.nPartId)
                                          .SingleOrDefault();

                        var convCurrPartM = myPartCtrl.ConvertFromCore(currPartM, MachGroupDbId);
                        if (currPart != null)
                        {
                            // se non identico x equality limitata a ViewOptim...
                            if (!currPart.ViewOptimEquals(convCurrPartM))
                            {
                                // aggiorno con nuovi valori ricevuti
                                currPart.H = convCurrPartM.H;
                                currPart.L = convCurrPartM.L;
                                currPart.W = convCurrPartM.W;
                                currPart.Material = convCurrPartM.Material;
                                currPart.CALC_State = convCurrPartM.CALC_State;
                                currPart.ROT = convCurrPartM.ROT;
                                currPart.PDN = convCurrPartM.PDN;
                                currPart.NAM = convCurrPartM.NAM;
                                // salvo
                                localDbCtx.SaveChanges();
                            }
                        }
                        else
                        {
                            PartList2Add.Add(convCurrPartM);
                        }
                    }

                    // aggiungo PartList
                    localDbCtx.PartList.AddRange(PartList2Add);
                    // Commit changes
                    localDbCtx.SaveChanges();

                    // aggiorno valore isNew a false x PROD
                    currData.IsNew = false;

                    // Commit changes
                    localDbCtx.SaveChanges();
                    // aggiorno info sullo status
                    myStatusMapCtrl.UpdateAction("", ProdId, newMachGroup.Id, Core.StatusMapItemType.MachGroup, Core.StatusMapOpType.MachGroupAdd, "");
                }
                catch (Exception exc)
                {
                    string errMessage = $"EXCEPTION on MachGroup.UpdateMachGroup: {Environment.NewLine}{exc}";
                    Console.WriteLine(errMessage);
                    Log.Error(errMessage);
                }
            }
            return currData;
        }

        /// <summary>
        /// Create record on DB
        /// </summary>
        /// <param name="newMachGroupId"></param>
        /// <param name="Name"></param>
        /// <returns></returns>
        public MachGroupModel Create(int newMachGroupId, string Name)
        {
            MachGroupModel newMachGroup = new MachGroupModel() { MachGroupId = newMachGroupId, Name = Name, State = Core.ItemState.ND };

            using (DatabaseContext localDbCtx = new DatabaseContext(DbConfig.CONNECTION_STRING))
            {
                try
                {
                    // Add to database
                    localDbCtx.MachGroupList.Add(newMachGroup);
                    // Commit changes
                    localDbCtx.SaveChanges();
                }
                catch (Exception exc)
                {
                    string errMessage = $"EXCEPTION on MachGroup.Create: {Environment.NewLine}{exc}";
                    Console.WriteLine(errMessage);
                    Log.Error(errMessage);
                }
            }
            return newMachGroup;
        }

        /// <summary>
        /// Delete MachGroup + Parts
        /// </summary>
        /// <param name="ProdId"></param>
        /// <param name="MachGroupId"></param>
        /// <returns></returns>
        public bool Delete(int ProdId, int MachGroupId)
        {
            bool done = false;
            using (DatabaseContext localDbCtx = new DatabaseContext(DbConfig.CONNECTION_STRING))
            {
                var myStatusMapCtrl = new StatusMapController();
                // inizio eliminando le part
                var parts2del = localDbCtx
                                .PartList
                                .Where(x => x.MachGroup.Prod.ProdId == ProdId && x.MachGroup.MachGroupId == MachGroupId)
                                .ToList();

                var MG2Del = localDbCtx
                                .MachGroupList
                                .Where(x => x.Prod.ProdId == ProdId && x.MachGroupId == MachGroupId)
                                .SingleOrDefault();

                try
                {
                    // Remove to database
                    localDbCtx.PartList.RemoveRange(parts2del);
                    localDbCtx.MachGroupList.Remove(MG2Del);
                    // Commit changes
                    localDbCtx.SaveChanges();

                    // registro modifica StatusMap
                    myStatusMapCtrl.UpdateAction(MG2Del.SupervisorId, ProdId, MG2Del.MachGroupId, Core.StatusMapItemType.MachGroup, Core.StatusMapOpType.MachGroupRem, "");

                    done = true;
                }
                catch (Exception exc)
                {
                    string errMessage = $"EXCEPTION on MachGroup.Delete: ProdId: {ProdId} | MachGroupId: {MachGroupId}{Environment.NewLine}{exc}";
                    Console.WriteLine(errMessage);
                    Log.Error(errMessage);
                }

                // se fatto aggiorno info sullo status
                myStatusMapCtrl.UpdateAction("", ProdId, MachGroupId, Core.StatusMapItemType.MachGroup, Core.StatusMapOpType.MachGroupRem, "");
            }
            return done;
        }

        public void Dispose()
        {
        }

        /// <summary>
        /// Get record by MachGroupDbId
        /// </summary>
        /// <param name="MachGroupDbId"></param>
        /// <returns></returns>
        public MachGroupModel FindByMachGroupDbId(int MachGroupDbId)
        {
            using (DatabaseContext localDbCtx = new DatabaseContext(DbConfig.CONNECTION_STRING))
            {
                return localDbCtx
                    .MachGroupList
                    .Where(x => x.MachGroupDbId == MachGroupDbId)
                    .SingleOrDefault();
            }
        }

        /// <summary>
        /// Get record by MachGroupId
        /// </summary>
        /// <param name="MachGroupId"></param>
        /// <returns></returns>
        public MachGroupModel FindByMachGroupId(int ProdId, int MachGroupId)
        {
            using (DatabaseContext localDbCtx = new DatabaseContext(DbConfig.CONNECTION_STRING))
            {
                return localDbCtx
                .MachGroupList
                .Where(x => x.Prod.ProdId == ProdId && x.MachGroupId == MachGroupId)
                .SingleOrDefault();
            }
        }

        /// <summary>
        /// Get filtered data by ProdId (ASC ordered)
        /// </summary>
        /// <param name="ProdId"></param>
        /// <returns></returns>
        public List<MachGroupModel> GetByProdAsc(int ProdId)
        {
            // verificare fattibilità in 1 solo passo
            int ProdDbId = 0;
            List<MachGroupModel> answ = new List<MachGroupModel>();
            using (DatabaseContext localDbCtx = new DatabaseContext(DbConfig.CONNECTION_STRING))
            {
                try
                {
                    var currProd = localDbCtx
                                    .ProdList
                                    .Where(x => x.ProdId == ProdId)
                                    .FirstOrDefault();
                    if (currProd != null)
                    {
                        ProdDbId = currProd.ProdDbId;
                    }
                }
                catch (Exception exc)
                {
                    string errMessage = $"EXCEPTION on MachGroup.GetByProdAsc: {Environment.NewLine}{exc}";
                    Console.WriteLine(errMessage);
                    Log.Error(errMessage);
                }
                answ = localDbCtx
                        .MachGroupList
                        .Where(x => x.ProdDbId == ProdDbId)
                        .OrderBy(x => x.ProdIndex)
                        .ThenBy(x => x.MachGroupId)
                        .ToList();
            }
            return answ;
        }

        /// <summary>
        /// Get filtered data by MachGroupectId (DESC ordered)
        /// </summary>
        /// <param name="ProdDbId"></param>
        /// <returns></returns>
        public List<MachGroupModel> GetByProdDesc(int ProdId)
        {
            // recupero
            int ProdDbId = 0;
            List<MachGroupModel> answ = new List<MachGroupModel>();
            using (DatabaseContext localDbCtx = new DatabaseContext(DbConfig.CONNECTION_STRING))
            {
                // verificare fattibilità in 1 solo passo
                try
                {
                    var currProd = localDbCtx
                                    .ProdList
                                    .Where(x => x.ProdId == ProdId)
                                    .FirstOrDefault();
                    if (currProd != null)
                    {
                        ProdDbId = currProd.ProdDbId;
                    }
                }
                catch (Exception exc)
                {
                    string errMessage = $"EXCEPTION on MachGroup.GetByProdDesc: {Environment.NewLine}{exc}";
                    Console.WriteLine(errMessage);
                    Log.Error(errMessage);
                }
                answ = localDbCtx
                        .MachGroupList
                        .Where(x => x.ProdDbId == ProdDbId)
                        .OrderByDescending(x => x.ProdIndex)
                        .ThenByDescending(x => x.MachGroupId)
                        .ToList();
            }
            return answ;
        }

        /// <summary>
        /// Get filtered data by Assign (ASC ordered)
        /// </summary>
        /// <param name="ProdId"></param>
        /// <param name="SupervisorId"></param>
        /// <returns></returns>
        public List<MachGroupModel> GetByProdSupervisor(int ProdId, string SupervisorId)
        {
            using (DatabaseContext localDbCtx = new DatabaseContext(DbConfig.CONNECTION_STRING))
            {
                return localDbCtx
                        .MachGroupList
                        .Where(x => x.Prod.ProdId == ProdId && x.SupervisorId == SupervisorId)
                        .OrderBy(x => x.ProdIndex)
                        .ThenBy(x => x.MachGroupId)
                        .ToList();
            }
        }

        /// <summary>
        /// Set ProdIndex for MachGroup
        /// </summary>
        /// <param name="ProdId"></param>
        /// <returns></returns>
        public int GetMinIndex(int ProdId)
        {
            int answ = 5000;
            using (DatabaseContext localDbCtx = new DatabaseContext(DbConfig.CONNECTION_STRING))
            {
                try
                {
                    // aggiorno
                    var result = localDbCtx
                                    .MachGroupList
                                    .Where(x => x.Prod.ProdId == ProdId && x.ProdIndex >= 5000 && x.ProdIndex < 10000)
                                    .OrderByDescending(x => x.ProdIndex)
                                    .FirstOrDefault();
                    if (result != null)
                    {
                        answ = result.ProdIndex;
                    }
                }
                catch (Exception exc)
                {
                    string errMessage = $"EXCEPTION on MachGroup.UpdateOrder: {Environment.NewLine}{exc}";
                    Console.WriteLine(errMessage);
                    Log.Error(errMessage);
                }
            }

            return answ;
        }

        /// <summary>
        /// Imposta a RIMOSSA dal supervisore
        /// </summary>
        /// <param name="MachGroupId"></param>
        /// <param name="newState"></param>
        /// <returns></returns>
        public bool RemoveFromSupervisor(int ProdId, int MachGroupId)
        {
            bool done = false;
            using (DatabaseContext localDbCtx = new DatabaseContext(DbConfig.CONNECTION_STRING))
            {
                var myStatusMapCtrl = new StatusMapController();
                try
                {
                    // aggiorno
                    var currRecord = localDbCtx
                                        .MachGroupList
                                        .Where(x => x.Prod.ProdId == ProdId && x.MachGroupId == MachGroupId)
                                        .FirstOrDefault();
                    if (currRecord != null)
                    {
                        currRecord.State = Core.ItemState.ND;
                        currRecord.SupervisorId = "";
                        currRecord.ProdIndex = 0;
                        // Commit changes
                        localDbCtx.SaveChanges();
                        // aggiorno info sullo status
                        myStatusMapCtrl.UpdateAction("", ProdId, MachGroupId, Core.StatusMapItemType.MachGroup, Core.StatusMapOpType.MachGroupRemovedFromSupervisor, "");

                        done = true;
                    }
                    else
                    {
                        string errMessage = $"ERROR on MachGroup.RemoveFromSupervisor: req item was not found | ProdId {ProdId} | MachGroupId {MachGroupId}";
                        Console.WriteLine(errMessage);
                        Log.Error(errMessage);
                    }
                }
                catch (Exception exc)
                {
                    string errMessage = $"EXCEPTION on MachGroup.RemoveFromSupervisor: {Environment.NewLine}{exc}";
                    Console.WriteLine(errMessage);
                    Log.Error(errMessage);
                }
            }
            return done;
        }

        /// <summary>
        /// Set MachGroup as NeedRedo (ripresa = da rigenerare)
        /// </summary>
        /// <param name="MachGroupId"></param>
        /// <param name="newState"></param>
        /// <param name="Value">Value to save for regenerate</param>
        /// <returns></returns>
        public bool SetNeedRedo(int ProdId, int MachGroupId, Core.ItemState newState, string Value)
        {
            bool done = false;
            using (DatabaseContext localDbCtx = new DatabaseContext(DbConfig.CONNECTION_STRING))
            {
                var myStatusMapCtrl = new StatusMapController();
                try
                {
                    // aggiorno
                    var item2upd = localDbCtx
                        .MachGroupList
                        .Where(x => x.Prod.ProdId == ProdId && x.MachGroupId == MachGroupId)
                        .FirstOrDefault();
                    if (item2upd != null)
                    {
                        item2upd.State = newState;
                        // Commit changes
                        localDbCtx.SaveChanges();
                        done = true;
                        // aggiorno info sullo status
                        myStatusMapCtrl.UpdateAction("", ProdId, MachGroupId, Core.StatusMapItemType.MachGroup, Core.StatusMapOpType.MachGroupNeedRedo, Value);
                    }
                    else
                    {
                        string errMessage = $"ERROR on MachGroup.SetNeedRedo: req item was not found | ProdId {ProdId} | MachGroupId {MachGroupId} | newState {newState} | Value {Value}";
                        Console.WriteLine(errMessage);
                        Log.Error(errMessage);
                    }
                }
                catch (Exception exc)
                {
                    string errMessage = $"EXCEPTION on MachGroup.SetNeedRedo: {Environment.NewLine}{exc}";
                    Console.WriteLine(errMessage);
                    Log.Error(errMessage);
                }
            }
            return done;
        }

        /// <summary>
        /// Update single MachGroup
        /// </summary>
        /// <param name="updItem">Item to update (with updated values)</param>
        /// <returns></returns>
        public bool Update(MachGroupModel updItem)
        {
            bool done = false;
            using (DatabaseContext localDbCtx = new DatabaseContext(DbConfig.CONNECTION_STRING))
            {
                var myStatusMapCtrl = new StatusMapController();
                try
                {
                    var item2update = localDbCtx
                                        .MachGroupList
                                        .Where(x => x.MachGroupDbId == updItem.MachGroupDbId)
                                        .SingleOrDefault();
                    if (item2update != null)
                    {
                        // update, vers 1...
                        localDbCtx.Entry(item2update).CurrentValues.SetValues(updItem);

                        // Commit changes
                        localDbCtx.SaveChanges();
                        done = true;
                        // aggiorno info sullo status
                        myStatusMapCtrl.UpdateAction("", updItem.Prod.ProdId, updItem.MachGroupId, Core.StatusMapItemType.MachGroup, Core.StatusMapOpType.MachGroupMod, "");
                    }
                    else
                    {
                        string errMessage = $"ERROR on MachGroup.Update: req item was not found | ProdDbId {updItem.ProdDbId} | MachGroupId {updItem.MachGroupId} | ProdIndex {updItem.ProdIndex}";
                        Console.WriteLine(errMessage);
                        Log.Error(errMessage);
                    }
                }
                catch (Exception exc)
                {
                    string errMessage = $"EXCEPTION on MachGroup.Update: {Environment.NewLine}{exc}";
                    Console.WriteLine(errMessage);
                    Log.Error(errMessage);
                }
            }
            return done;
        }

        /// <summary>
        /// Set END for MachGroup
        /// </summary>
        /// <param name="ProdId"></param>
        /// <param name="MachGroupId"></param>
        /// <param name="DtEnd"></param>
        /// <returns></returns>
        public bool UpdateEnd(int ProdId, int MachGroupId, DateTime DtEnd)
        {
            bool done = false;
            using (DatabaseContext localDbCtx = new DatabaseContext(DbConfig.CONNECTION_STRING))
            {
                var myStatusMapCtrl = new StatusMapController();
                try
                {
                    // aggiorno
                    var currRecord = localDbCtx
                                        .MachGroupList
                                        .Where(x => x.Prod.ProdId == ProdId && x.MachGroupId == MachGroupId)
                                        .FirstOrDefault();
                    if (currRecord != null)
                    {
                        currRecord.DtEnd = DtEnd;
                        // Commit changes
                        localDbCtx.SaveChanges();
                        done = true;
                        // aggiorno info sullo status
                        myStatusMapCtrl.UpdateAction("", ProdId, MachGroupId, Core.StatusMapItemType.MachGroup, DtEnd == DateTime.MinValue ? Core.StatusMapOpType.ResetPartEnd : Core.StatusMapOpType.PartEnd, "");
                    }
                    else
                    {
                        string errMessage = $"ERROR on MachGroup.UpdateEnd: req item was not found | ProdId {ProdId} | MachGroupId {MachGroupId} | DtEnd {DtEnd}";
                        Console.WriteLine(errMessage);
                        Log.Error(errMessage);
                    }
                }
                catch (Exception exc)
                {
                    string errMessage = $"EXCEPTION on MachGroup.UpdateEnd: {Environment.NewLine}{exc}";
                    Console.WriteLine(errMessage);
                    Log.Error(errMessage);
                }
            }
            return done;
        }

        /// <summary>
        /// Set ProdIndex for MachGroup
        /// </summary>
        /// <param name="ProdId"></param>
        /// <param name="MachGroupId"></param>
        /// <param name="newProdIndex"></param>
        /// <returns></returns>
        public bool UpdateOrder(int ProdId, int MachGroupId, int newProdIndex)
        {
            bool done = false;
            using (DatabaseContext localDbCtx = new DatabaseContext(DbConfig.CONNECTION_STRING))
            {
                try
                {
                    // aggiorno
                    var item2upd = localDbCtx
                        .MachGroupList
                        .Where(x => x.Prod.ProdId == ProdId && x.MachGroupId == MachGroupId)
                        .FirstOrDefault();
                    if (item2upd != null)
                    {
                        item2upd.ProdIndex = newProdIndex;
                        // Commit changes
                        localDbCtx.SaveChanges();
                        done = true;
                    }
                    else
                    {
                        string errMessage = $"ERROR on MachGroup.UpdateOrder: req item was not found | ProdId {ProdId} | MachGroupId {MachGroupId} | newProdIndex {newProdIndex}";
                        Console.WriteLine(errMessage);
                        Log.Error(errMessage);
                    }
                }
                catch (Exception exc)
                {
                    string errMessage = $"EXCEPTION on MachGroup.UpdateOrder: {Environment.NewLine}{exc}";
                    Console.WriteLine(errMessage);
                    Log.Error(errMessage);
                }
            }
            return done;
        }

        /// <summary>
        /// Set START for MachGroup
        /// </summary>
        /// <param name="ProdId"></param>
        /// <param name="MachGroupId"></param>
        /// <param name="PartId"></param>
        /// <param name="DtStart"></param>
        /// <returns></returns>
        public bool UpdateStart(int ProdId, int MachGroupId, DateTime DtStart)
        {
            bool done = false;
            using (DatabaseContext localDbCtx = new DatabaseContext(DbConfig.CONNECTION_STRING))
            {
                var myStatusMapCtrl = new StatusMapController();
                try
                {
                    // aggiorno
                    var currRecord = localDbCtx
                                        .MachGroupList
                                        .Where(x => x.Prod.ProdId == ProdId && x.MachGroupId == MachGroupId)
                                        .FirstOrDefault();
                    if (currRecord != null)
                    {
                        currRecord.DtStart = DtStart;
                        // Commit changes
                        localDbCtx.SaveChanges();
                        done = true;
                        // aggiorno info sullo status
                        myStatusMapCtrl.UpdateAction("", ProdId, MachGroupId, Core.StatusMapItemType.MachGroup, DtStart == DateTime.MinValue ? Core.StatusMapOpType.ResetPartStart : Core.StatusMapOpType.PartStart, "");
                    }
                    else
                    {
                        string errMessage = $"ERROR on MachGroup.UpdateStart: req item was not found | ProdId {ProdId} | MachGroupId {MachGroupId} | DtStart {DtStart}";
                        Console.WriteLine(errMessage);
                        Log.Error(errMessage);
                    }
                }
                catch (Exception exc)
                {
                    string errMessage = $"EXCEPTION on MachGroup.UpdateStart: {Environment.NewLine}{exc}";
                    Console.WriteLine(errMessage);
                    Log.Error(errMessage);
                }
            }
            return done;
        }

        /// <summary>
        /// Set START/END for MachGroup
        /// </summary>
        /// <param name="ProdId"></param>
        /// <param name="MachGroupId"></param>
        /// <param name="DtStart"></param>
        /// <param name="DtEnd"></param>
        /// <returns></returns>
        public bool UpdateStartEnd(int ProdId, int MachGroupId, DateTime DtStart, DateTime DtEnd)
        {
            bool done = false;
            using (DatabaseContext localDbCtx = new DatabaseContext(DbConfig.CONNECTION_STRING))
            {
                var myStatusMapCtrl = new StatusMapController();
                try
                {
                    // aggiorno
                    var currRecord = localDbCtx
                                        .MachGroupList
                                        .Where(x => x.Prod.ProdId == ProdId && x.MachGroupId == MachGroupId)
                                        .FirstOrDefault();
                    if (currRecord != null)
                    {
                        currRecord.DtStart = DtStart;
                        currRecord.DtEnd = DtEnd;
                        // Commit changes
                        localDbCtx.SaveChanges();
                        done = true;
                        // aggiorno info sullo status
                        myStatusMapCtrl.UpdateAction("", ProdId, MachGroupId, Core.StatusMapItemType.MachGroup, Core.StatusMapOpType.MachGroupMod, "");
                    }
                    else
                    {
                        string errMessage = $"ERROR on MachGroup.UpdateStartEnd: req item was not found | ProdId {ProdId} | MachGroupId {MachGroupId} | DtStart {DtStart} | DtEnd {DtEnd}";
                        Console.WriteLine(errMessage);
                        Log.Error(errMessage);
                    }
                }
                catch (Exception exc)
                {
                    string errMessage = $"EXCEPTION on MachGroup.UpdateStartEnd: {Environment.NewLine}{exc}";
                    Console.WriteLine(errMessage);
                    Log.Error(errMessage);
                }
            }
            return done;
        }

        /// <summary>
        /// Set Status for MachGroup
        /// </summary>
        /// <param name="MachGroupId"></param>
        /// <param name="newState"></param>
        /// <returns></returns>
        public bool UpdateStatus(int ProdId, int MachGroupId, Core.ItemState newState)
        {
            bool done = false;
            using (DatabaseContext localDbCtx = new DatabaseContext(DbConfig.CONNECTION_STRING))
            {
                var myStatusMapCtrl = new StatusMapController();
                try
                {
                    // aggiorno
                    var item2upd = localDbCtx
                        .MachGroupList
                        .Where(x => x.Prod.ProdId == ProdId && x.MachGroupId == MachGroupId)
                        .FirstOrDefault();
                    if (item2upd != null)
                    {
                        item2upd.State = newState;
                        // Commit changes
                        localDbCtx.SaveChanges();
                        done = true;
                        // aggiorno info sullo status
                        myStatusMapCtrl.UpdateAction("", ProdId, MachGroupId, Core.StatusMapItemType.MachGroup, Core.StatusMapOpType.MachGroupMod, "");
                    }
                    else
                    {
                        string errMessage = $"ERROR on MachGroup.UpdateStatus: req item was not found | ProdId {ProdId} | MachGroupId {MachGroupId} | newState {newState}";
                        Console.WriteLine(errMessage);
                        Log.Error(errMessage);
                    }
                }
                catch (Exception exc)
                {
                    string errMessage = $"EXCEPTION on MachGroup.UpdateStatus: {Environment.NewLine}{exc}";
                    Console.WriteLine(errMessage);
                    Log.Error(errMessage);
                }
            }
            return done;
        }

        /// <summary> Set Supervisor & state for MachGroup </summary> <param name="ProdId"></param>
        /// <param name="MachGroupId"></param> <param name="SupervisorId"></param> <returns></returns>
        public bool UpdateSupervisor(int ProdId, int MachGroupId, string SupervisorId)
        {
            bool done = false;
            using (DatabaseContext localDbCtx = new DatabaseContext(DbConfig.CONNECTION_STRING))
            {
                var myStatusMapCtrl = new StatusMapController();
                try
                {
                    // aggiorno
                    var item2upd = localDbCtx
                                        .MachGroupList
                                        .Where(x => x.Prod.ProdId == ProdId && x.MachGroupId == MachGroupId)
                                        .FirstOrDefault();
                    if (item2upd != null)
                    {
                        item2upd.SupervisorId = SupervisorId;
                        item2upd.State = Core.ItemState.Assigned;

                        // Commit changes
                        localDbCtx.SaveChanges();
                        done = true;

                        // aggiorno info sullo status
                        myStatusMapCtrl.UpdateAction("", ProdId, MachGroupId, Core.StatusMapItemType.MachGroup, Core.StatusMapOpType.MachGroupAssignedToSupervisor, "");
                    }
                    else
                    {
                        string errMessage = $"ERROR on MachGroup.UpdateSupervisor: req item was not found | ProdId {ProdId} | MachGroupId {MachGroupId} | SupervisorId {SupervisorId}";
                        Console.WriteLine(errMessage);
                        Log.Error(errMessage);
                    }
                }
                catch (Exception exc)
                {
                    string errMessage = $"EXCEPTION on MachGroup.UpdateSupervisor: {Environment.NewLine}{exc}";
                    Console.WriteLine(errMessage);
                    Log.Error(errMessage);
                }
            }
            return done;
        }

        #endregion Public Methods

        #region Private Fields

        /// <summary>
        /// Istanza logger
        /// </summary>
        private NLog.Logger Log = LogManager.GetCurrentClassLogger();

        #endregion Private Fields
    }
}