public SequencingStation GetSequencingStationSettingsById(int id)
        {
            PartSequencingDataContext dbSeq = new PartSequencingDataContext();
            HP_MESDataContext dbMes = new HP_MESDataContext();

            var result = (from s in SequencingSettingsCacheManager.SequencingStationSettings where s.Id == id select s).Single();

            var baseStation = SequencingSettingsCacheManager.BaseSequencingStationOffsets.Where(x => x.LineId == result.LineId).Single();

            
           var setting = new SequencingStation
            {
                Description = result.Description,
                Id = result.Id,
                SequencingLocation = dbSeq.SequencingLocations.Where(x => x.Id == result.SequencingLocationId).Single(),
                Line = dbSeq.Lines.Where(x => x.Id == result.LineId).Single(),
                Station = GetStation((int)result.StationId),
                StationOrder = (int)result.StationOrder,
                BoxPerSchedule = (int)result.BoxPerSchedule,
                BoxQty = (int)result.BoxQty,
                MessageFormat = result.MessageFormat,
                Obsolete = (bool)result.Obsolete,
                PartsPerBox = (int)result.PartsPerBox,
                SeatOptions = (int)result.SeatOptions,
                SeatOptions2Check = (int)result.SeatOptions2Check,
                Status = false,
                Offset = (int)result.Offset,
                BaseStation = SequencingSettingsCacheManager.SequencingStationSettings.Where(x => x.Id == baseStation.SequencingStationSettingsId).Single()
            };

            return setting;
        }
        public IEnumerable<TempBuffer> GetSequencingBuffer(SequencingStation station)
        {
            PartSequencingDataContext dbSeq = new PartSequencingDataContext();
            HP_MESDataContext dbMes = new HP_MESDataContext();
            SequencingDatabase db = new SequencingDatabase();

            List<TempBuffer> lineBuffer = null;

            string groupLine = station.SequencingLocation.LineGroup.Trim();
            int lineId = station.Line.Id;
            int locationId = station.SequencingLocation.Id;
            if (station.SequencingLocation.ParentId == null)
            {
                lineBuffer = (from s in dbSeq.SEQ_SP_GetSequencingBufferBySeqId(station.Id)
                              select new TempBuffer
                              {
                                  Group = groupLine,
                                  //ItemNumber = "1800VR",
                                  ItemNumber = s.ItemNumber.Trim(),
                                  ItemType = s.ItemType.Trim(),
                                  JobId = (int)s.JobId,
                                  OrderId = (int)s.OrderId,
                                  OrderStatus = (int)s.OrderStatus,
                                  Region = s.Region.Trim(),
                                  LineId = (int)s.LineId,
                                  OrderNumber = s.OrderNumber,
                                  BuildDTM = s.BuildDTM == null ? "" : s.BuildDTM.Value.ToString("mm/dd/yyyy hh:mm:ss tt")
                              }).ToList();
            }
            else
            {

                lineBuffer = (from s in dbSeq.IWS_GetSequencingStationQueueByLocationId(locationId)
                              select new TempBuffer
                              {
                                  ScheduleNum = (int)s.ScheduleNum,
                                  BoxNum = (int)s.BoxNum,
                                  OrderNumber = s.OrderNumber == null ? "" : s.OrderNumber.Trim(),
                                  Group = groupLine,
                                  //ItemNumber = "1420CF",
                                  ItemNumber = s.ItemNumber.Trim(),
                                  ItemType = s.ItemType.Trim(),
                                  JobId = (int)s.JobId,
                                  OrderId = (int)s.OrderId,
                                  OrderStatus = (int)s.OrderStatus,
                                  Region = s.Region.Trim(),
                                  LineId = lineId
                              }).ToList();

            }

            return lineBuffer;
        }
        public void UpdateSequencingStationSettingsById(SequencingStation newSetting)
        {
            PartSequencingDataContext db = new PartSequencingDataContext();
            var setting = (from s in db.SequencingStationSettings where s.Id == newSetting.Id select s).Single();
            setting.BoxPerSchedule = newSetting.BoxPerSchedule;
            setting.BoxQty = newSetting.BoxQty;
            setting.Description = newSetting.Description;
            setting.MessageFormat = newSetting.MessageFormat;
            setting.Obsolete = newSetting.Obsolete;
            setting.PartsPerBox = newSetting.PartsPerBox;
            setting.SeatOptions = newSetting.SeatOptions;
            setting.SeatOptions2Check = newSetting.SeatOptions2Check;
            setting.StationOrder = newSetting.StationOrder;
            setting.Offset = newSetting.Offset;
            db.SubmitChanges();

            SequencingSettingsCacheManager.RefreshSequencingStationSettings();
        }
        public IEnumerable<SequencingTrackingItem> GetAdminSequencingHistory(SequencingStation station)
        {
            PartSequencingDataContext dbSeq = new PartSequencingDataContext();

            var tracking = (from s in dbSeq.SEQ_SP_GetSequencingHistoryEOLBySeqId(station.Id)
                            select new SequencingTrackingItem
                            {
                                BoxNum = s.BoxNum,
                                DTM = s.DTM,
                                ItemNumber = s.ItemNumber,
                                ItemType = s.ItemType,
                                ScheduleNum = s.ScheduleNum,
                                OrderId = s.OrderId,
                                SequencingStationSettingsId = s.SequencingStationSettingsId,
                                SequencingTrackingHistoryDetailsId = s.SequencingTrackingHistoryDetailId,
                                SequencingTrackingHistoryId = s.SequencingTrackingHistoryId,
                                Type = (int)s.Type
                            }).ToList();
            return tracking;
        }
        public IEnumerable<SequencingTrackingItem> GetSequencingHistory(SequencingStation station)
        {
            PartSequencingDataContext dbSeq = new PartSequencingDataContext();

            var tracking = (dbSeq.SequencingTrackingHistoryDetails.Where(
                    i => i.SequencingStationSettingsId == station.Id).Join(
                    dbSeq.SequencingTrackingHistories, th => th.Id,
                    ti => ti.SequencingTrackingHistoryDetailId, (th, ti) => new SequencingTrackingItem
                    {
                        OrderNumber = ti.OrderNumber,
                        BoxNum = th.BoxNum,
                        DTM = th.DTM,
                        ItemNumber = ti.ItemNumber,
                        ItemType = ti.ItemType,
                        ScheduleNum = th.ScheduleNum,
                        OrderId = ti.OrderId,
                        SequencingStationSettingsId = th.SequencingStationSettingsId,
                        SequencingTrackingHistoryDetailsId = (int)ti.SequencingTrackingHistoryDetailId,
                        SequencingTrackingHistoryId = ti.Id,
                        Type = (int)th.Type
                    })).ToList();

            return tracking;
        }
        private TrimScheduleStatus GetTrimScheduleStatus(SequencingStation station, SequencingStationLookup lookup, List<Seat> seatSchedule)
        {
            TrimScheduleStatus status = new TrimScheduleStatus();

            if (station.SequencingLocation.ParentId == null)
            {
                status.CurrentBoxNumber = lookup.NextBoxNum;
                status.CurrentScheduleNumber = lookup.NextScheduleNum;
            }
            else //from queue table
            {
                var firstjob = seatSchedule.FirstOrDefault();
                if (firstjob != null)
                {
                    status.CurrentBoxNumber = firstjob.BoxNum;
                    status.CurrentScheduleNumber = firstjob.ScheduleNum;
                }
                else
                {
                    status.CurrentBoxNumber = lookup.NextBoxNum;
                    status.CurrentScheduleNumber = lookup.NextScheduleNum;
                }
            }

            return status;
        }
        public string GetSequencingMessage(SequencingStation station, string itemNumber, IEnumerable<MessageToken> lineTokens)
        {
            #region Get Sequencing Message
            ItemDetailsFactory itemDetailsModel = new ItemDetailsFactory();
            var item = itemDetailsModel.GetItemInfo(itemNumber);

            if (item == null)
                return String.Format("*Unknown Part* ({0})", itemNumber);

            string[] tokens = station.MessageFormat.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

            var formattedMsg = station.MessageFormat.Trim();

            if (tokens[0] == null) throw new NotImplementedException();


            var filteredParts = item.ItemInfos.Where(
                                part =>
                                ((ItemDetailsFactory.GetBuildcodeOption(part) & station.SeatOptions) ==
                                 (ItemDetailsFactory.GetBuildcodeOption(part) & station.SeatOptions2Check) &&
                                 (ItemDetailsFactory.GetBuildcodeOption(part) & station.SeatOptions) == (station.SeatOptions & station.SeatOptions2Check) &&
                                 part.LineId == station.Line.Id)).OrderBy(part => part.PartIndex).ToList();

            List<MessageToken> validLineTokens = lineTokens.Where(t => tokens.Contains(t.Token.Trim())).ToList();
            var colourExtensions = MessageTokensCacheManager.ColourExtensions;
            var trimExtensions = MessageTokensCacheManager.TrimExtensions;

            if (filteredParts.Count() > 0)
            {
                ItemInfo part = null;

                if (station.Line.Id == 1 || station.Line.Id == 2)
                    part = filteredParts.Where(p => p.PartIndex == 1).FirstOrDefault();
                else if (station.Line.Id == 3)
                    part = filteredParts.Where(p => p.PartIndex == 3).FirstOrDefault();

                if (part != null)
                {
                    //3Pass ONLY
                    if (part.ItemComponent == "NO-2LH" || part.ItemComponent == "NO-2RH")
                        return String.Format("NO BUILD ({0})", itemNumber);
                    
                    //iterate through and look or feneric options number replacement
                    foreach (var specialOption in tokens)
                    {
                        if (specialOption.Contains("OPTION"))
                        {
                            var optionNumberString = new String(specialOption.Where(Char.IsDigit).ToArray());
                            formattedMsg = formattedMsg.Replace(specialOption.Trim(), ItemDetailsFactory.GetOptionValue(part, int.Parse(optionNumberString)));
                        }
                    }

                    foreach (var token in validLineTokens)
                    {
                        var _trimstyle = ItemDetailsFactory.GetOptionValue(part, 100);
                        var _colour = ItemDetailsFactory.GetOptionValue(part, 101);
                        var _isRU = ItemDetailsFactory.IsRU(part.ItemType);

                        switch (token.SpecialValue.Trim())
                        {
                            case "8PASS":
                                #region 8PASS
                                if (_isRU)
                                {
                                    var _8pass = ItemDetailsFactory.GetOptionValue(part, 115);
                                    if (_8pass.Equals("8PASS"))
                                        formattedMsg = formattedMsg.Replace(token.Token.Trim(), token.MessageTrue.Trim());
                                }
                                formattedMsg = formattedMsg.Replace(token.Token.Trim(), token.MessageFalse.Trim());
                                break;
                                #endregion
                            case "7PASS":
                                #region 7PASS
                                if (_isRU)
                                {
                                    var _8pass = ItemDetailsFactory.GetOptionValue(part, 115);
                                    if (!_8pass.Equals("8PASS"))
                                        formattedMsg = formattedMsg.Replace(token.Token.Trim(), token.MessageTrue.Trim());
                                }
                                formattedMsg = formattedMsg.Replace(token.Token.Trim(), token.MessageFalse.Trim());
                                break;
                                #endregion
                            case "RU":
                                #region RU
                                if (_isRU)
                                    formattedMsg = formattedMsg.Replace(token.Token.Trim(), token.MessageTrue.Trim());
                                formattedMsg = formattedMsg.Replace(token.Token.Trim(), token.MessageFalse.Trim());
                                break;
                            #endregion
                            case "3PMANSHIELD":
                                #region 3PMANSHIELD
                                if (_isRU)
                                {
                                    //TODO:
                                    formattedMsg = formattedMsg.Replace(token.Token.Trim(), token.MessageFalse.Trim());
                                }
                                else
                                {
                                    if (_colour.Equals("R4") || _colour.Equals("X9") || ItemDetailsFactory.GetOptionValue(part, 3) == "PWR")
                                        formattedMsg = formattedMsg.Replace(token.Token.Trim(), token.MessageTrue.Trim());
                                    formattedMsg = formattedMsg.Replace(token.Token.Trim(), token.MessageFalse.Trim());
                                }
                                break;
                            #endregion
                            case "3PPWRSHIELD":
                                #region 3PPWRSHIELD
                                var _pwr = "";
                                if (_isRU)
                                    _pwr = ItemDetailsFactory.GetOptionValue(part, 103);
                                else
                                    _pwr = ItemDetailsFactory.GetOptionValue(part, 3);

                                if (_pwr == "PWR")
                                    formattedMsg = formattedMsg.Replace(token.Token.Trim(), token.MessageFalse.Trim());
                                formattedMsg = formattedMsg.Replace(token.Token.Trim(), token.MessageTrue.Trim());

                                break;
                            #endregion
                            case "3PMAN!RQ":
                                #region 3PMAN!RQ
                                var _pwr2 = "";
                                if (_isRU)
                                    _pwr2 = ItemDetailsFactory.GetOptionValue(part, 103);
                                else
                                    _pwr2 = ItemDetailsFactory.GetOptionValue(part, 3);

                                if (_pwr2 != "PWR")
                                    formattedMsg = formattedMsg.Replace(token.Token.Trim(), token.MessageTrue.Trim());
                                formattedMsg = formattedMsg.Replace(token.Token.Trim(), token.MessageFalse.Trim());
                                break;
                            #endregion
                            case "3PX9MAN!RQ":
                                #region 3PX9MAN!RQ
                                if (_isRU)
                                {
                                    //TODO:
                                    //formattedMsg = _trimstyle + " " + _colour;
                                }
                                else
                                {
                                    if (_colour.Equals("R4") || _colour.Equals("X9"))
                                    {
                                        if (ItemDetailsFactory.GetOptionValue(part, 3) != "PWR")
                                            formattedMsg = formattedMsg.Replace(token.Token.Trim(), token.MessageTrue.Trim());
                                    }
                                }
                                formattedMsg = formattedMsg.Replace(token.Token.Trim(), token.MessageFalse.Trim());
                                break;
                            #endregion
                            case "RMVQD!RQ":
                                #region RMVQD!RQ
                                if (_isRU)
                                {
                                    formattedMsg = formattedMsg.Replace(token.Token.Trim(), token.MessageFalse.Trim());
                                }
                                else
                                {
                                    if (ItemDetailsFactory.GetOptionValue(part, 11) == "LXQD")
                                        formattedMsg = formattedMsg.Replace(token.Token.Trim(), token.MessageTrue.Trim());
                                    formattedMsg = formattedMsg.Replace(token.Token.Trim(), token.MessageFalse.Trim());
                                }
                                break;
                            #endregion
                            case "PWRCARPET":
                                #region PWRCARPET
                                if (_isRU)
                                {
                                    //TODO:
                                    //formattedMsg = _trimstyle + " " + _colour;
                                }
                                else
                                {
                                    if (ItemDetailsFactory.GetOptionValue(part, 3) == "PWR")
                                    {
                                        if (_colour.Equals("D1"))
                                            formattedMsg = formattedMsg.Replace(token.Token.Trim(), "(X9 Carpet)");
                                        else if (_colour.Equals("X9"))
                                            formattedMsg = formattedMsg.Replace(token.Token.Trim(), "(X9 Carpet)");
                                        else if (_colour.Equals("L9"))
                                            formattedMsg = formattedMsg.Replace(token.Token.Trim(), "(L5 Carpet)");
                                        else if (_colour.Equals("L5"))
                                            formattedMsg = formattedMsg.Replace(token.Token.Trim(), "(L5 Carpet)");
                                        else if (_colour.Equals("TU"))
                                            formattedMsg = formattedMsg.Replace(token.Token.Trim(), "(X9 Carpet)");
                                    }
                                    else
                                    {
                                        formattedMsg = formattedMsg.Replace(token.Token.Trim(), token.MessageTrue.Trim());
                                    }
                                }
                                formattedMsg = formattedMsg.Replace(token.Token.Trim(), token.MessageFalse.Trim());
                                break;
                            #endregion
                            case "POWERBOLD":
                                #region POWERBOLD
                                if (_isRU)
                                {
                                    //TODO:
                                    //formattedMsg = _trimstyle + " " + _colour;
                                }
                                else
                                {
                                    if (ItemDetailsFactory.GetOptionValue(part, 3) == "PWR")
                                        formattedMsg = formattedMsg.Replace(token.Token.Trim(), token.MessageTrue.Trim());
                                    formattedMsg = formattedMsg.Replace(token.Token.Trim(), token.MessageFalse.Trim());
                                }
                                break;
                            #endregion
                            case "SIDESHIELDCLR":
                                #region SIDESHIELD

                                var _shldclr = _colour;
                                if (colourExtensions != null)
                                {
                                    var _ext =
                                        colourExtensions.Where(
                                            cExt =>
                                            cExt.ColourCode == _shldclr && cExt.ExtensionName == "Side Shield").ToList();

                                    if (_ext.Count() > 0)
                                        _shldclr = _ext[0].ColourCodeExt.Trim();
                                }
                                formattedMsg = formattedMsg.Replace(token.Token.Trim(), _shldclr);

                                break;
                            #endregion
                            case "TRIMCLR":
                                #region TRIMCLR
                                if (_isRU)
                                {
                                    //TODO:
                                    //formattedMsg = _trimstyle + " " + _colour;
                                }
                                else
                                {
                                    var _trimclr = _colour;
                                    if (colourExtensions != null)
                                    {
                                        var _ext =
                                            colourExtensions.Where(
                                                cExt =>
                                                cExt.ColourCode == _trimclr && cExt.ExtensionName == "Trim").ToList();

                                        if (_ext.Count() > 0)
                                            _trimclr = _ext[0].ColourCodeExt.Trim();
                                    }
                                    formattedMsg = formattedMsg.Replace(token.Token.Trim(), _trimclr);
                                }
                                break;
                            #endregion
                            case "FRTSHIELD":
                                #region FRTSHIELD
                                if (_isRU)
                                {
                                    //TODO:
                                    //formattedMsg = _trimstyle + " " + _colour;
                                }
                                else
                                {
                                    if (_colour.Equals("R4") || _colour.Equals("X9"))
                                        formattedMsg = formattedMsg.Replace(token.Token.Trim(), token.MessageTrue.Trim());
                                    formattedMsg = formattedMsg.Replace(token.Token.Trim(), token.MessageFalse.Trim());
                                }
                                break;
                            #endregion
                            case "FRTASHIELD":
                                #region FRTASHIELD

                                if (_colour.Equals("X9") || _colour.Equals("R4"))
                                    formattedMsg = formattedMsg.Replace(token.Token.Trim(), token.MessageTrue);
                                else
                                {
                                    var _drvpart = filteredParts.Where(p => p.PartIndex == 1).FirstOrDefault();
                                    var _paspart = filteredParts.Where(p => p.PartIndex == 2).FirstOrDefault();

                                    string partstring1 = string.Empty;
                                    string partstring2 = string.Empty;

                                    if (ItemDetailsFactory.GetOptionValue(_drvpart, 1) == "DRV")
                                    {
                                        if (ItemDetailsFactory.GetOptionValue(_drvpart, 3) == "PWR")
                                            partstring1 = "580298-" + _colour + " PWR (DRV)";
                                        else
                                            partstring1 = "580278-" + _colour + " MAN (DRV)";
                                    }

                                    if (ItemDetailsFactory.GetOptionValue(_paspart, 1) == "PASS")
                                    {
                                        if (ItemDetailsFactory.GetOptionValue(_paspart, 3) == "PWR")
                                            partstring2 = "580288-" + _colour + " PWR (PASS)";
                                        else
                                            partstring2 = "580268-" + _colour + " MAN (PASS)";
                                    }

                                    formattedMsg = formattedMsg.Replace(token.Token.Trim(), partstring1 + "," + partstring2);
                                }

                                break;
                            #endregion
                            case "FRTCARPET":
                                #region FRTCARPET
                                if (_colour.Equals("D1"))
                                    formattedMsg = formattedMsg.Replace(token.Token.Trim(), "550608N-D1,550608N-D1");
                                else if (_colour.Equals("L5"))
                                    formattedMsg = formattedMsg.Replace(token.Token.Trim(), "550608N-L5,550608N-L5");
                                else if (_colour.Equals("L9"))
                                    formattedMsg = formattedMsg.Replace(token.Token.Trim(), "550608N-L9,550608N-L9");
                                else if (_colour.Equals("TU"))
                                    formattedMsg = formattedMsg.Replace(token.Token.Trim(), "550608N-TU,550608N-TU");
                                else
                                    formattedMsg = formattedMsg.Replace(token.Token.Trim(), token.MessageTrue);

                                break;
                            #endregion
                            case "ONLYLXQD":
                                #region ONLYLXQD
                                var _lxqd = "";
                                if (_isRU)
                                    _lxqd = ItemDetailsFactory.GetOptionValue(part, 103);
                                else
                                    _lxqd = ItemDetailsFactory.GetOptionValue(part, 11);


                                if (_lxqd.ToUpper() == "LXQD")
                                    formattedMsg = formattedMsg.Replace(token.Token.Trim(), token.MessageFalse.Trim());
                                formattedMsg = formattedMsg.Replace(token.Token.Trim(), token.MessageTrue.Trim());

                                break;
                            #endregion
                            case "BENCH":
                                #region BENCH
                                if (part.ItemType == "2B")
                                {
                                    if (_colour.Equals("D1") || _colour.Equals("L5") || _colour.Equals("TU"))
                                        formattedMsg = formattedMsg.Replace(token.Token.Trim(), token.MessageFalse.Trim());
                                }
                                formattedMsg = formattedMsg.Replace(token.Token.Trim(), token.MessageTrue.Trim());
                                break;
                            #endregion
                            case "TBENCH!RQ":
                                #region TBENCH!RQ

                                if (part.ItemType == "2B")
                                    formattedMsg = formattedMsg.Replace(token.Token.Trim(), token.MessageTrue.Trim());
                                formattedMsg = formattedMsg.Replace(token.Token.Trim(), token.MessageFalse.Trim());

                                break;
                            #endregion
                            case "TNOBUILD!RQ":
                                #region
                                if (_isRU)
                                {
                                    //TODO:
                                    //formattedMsg = _trimstyle + " " + _colour;
                                }
                                else
                                {
                                    if (part.ItemComponent.Trim() == "NO-2LH" || part.ItemComponent.Trim() == "NO-2RH")
                                        formattedMsg = formattedMsg.Replace(token.Token.Trim(), token.MessageTrue.Trim());
                                    formattedMsg = formattedMsg.Replace(token.Token.Trim(), token.MessageFalse.Trim());
                                }
                                break;
                            #endregion
                            case "CLOTH!RQ":
                                #region CLOTH!RQ
                                var cloth = "";
                                if (_isRU)
                                    cloth = ItemDetailsFactory.GetOptionValue(part, 108);
                                else
                                    cloth = ItemDetailsFactory.GetOptionValue(part, 5);

                                if (cloth.ToUpper() == "CLOTH")
                                {
                                    if (ItemDetailsFactory.GetOptionValue(part, 10).ToUpper() != "HT")
                                        formattedMsg = formattedMsg.Replace(token.Token.Trim(), token.MessageTrue.Trim());
                                }
                                formattedMsg = formattedMsg.Replace(token.Token.Trim(), token.MessageFalse.Trim());

                                break;
                            #endregion
                            case "H7N7X9!RQ":
                                #region H7N7X9!RQ
                                if (_isRU)
                                {
                                    //TODO:
                                }
                                else
                                {
                                    if (_trimstyle.Equals("H7") || _trimstyle.Equals("N7"))
                                    {
                                        if (_colour.Equals("X9") && ItemDetailsFactory.GetOptionValue(part, 9) != "BUX")
                                            formattedMsg = formattedMsg.Replace(token.Token.Trim(), token.MessageTrue.Trim());
                                    }
                                }
                                formattedMsg = formattedMsg.Replace(token.Token.Trim(), token.MessageFalse.Trim());
                                break;
                            #endregion
                            case "HDRCOLOUR":
                                #region HDRCOLOUR
                                var _hdrcolour = _colour;
                                if (colourExtensions != null)
                                {
                                    var _ext = colourExtensions.Where(cExt => cExt.ColourCode == _hdrcolour && cExt.ExtensionName == "Headrest").ToList();

                                    if (_ext.Count() > 0)
                                        _hdrcolour = _ext[0].ColourCodeExt.Trim();
                                }
                                formattedMsg = formattedMsg.Replace(token.Token.Trim(), _hdrcolour);
                                break;
                            #endregion
                            case "HDRTRIM":
                                #region HDRTRIM
                                var _hdrtrim = _trimstyle;
                                if (trimExtensions != null)
                                {
                                    var _ext = trimExtensions.Where(tExt => tExt.TrimCode == _hdrtrim && tExt.ExtensionName == "Headrest").ToList();
                                    if (_ext.Count() > 0)
                                        _hdrtrim = _ext[0].TrimCodeExt.Trim();
                                }
                                formattedMsg = formattedMsg.Replace(token.Token.Trim(), _hdrtrim);
                                break;
                            #endregion
                            case "X9R4!RQ":
                                #region X9R4!RQ
                                if (_isRU)
                                {
                                    var sng = ItemDetailsFactory.GetOptionValue(part, 114);
                                    if (sng == "SNG")
                                    {
                                        if (_colour.Equals("X9") || _colour.Equals("R4"))
                                            formattedMsg = formattedMsg.Replace(token.Token.Trim(), token.MessageTrue);
                                    }
                                    formattedMsg = formattedMsg.Replace(token.Token.Trim(), token.MessageFalse.Trim());
                                }
                                else
                                {
                                    var sng = ItemDetailsFactory.GetOptionValue(part, 13);
                                    if (sng == "SNG")
                                    {
                                        if (_colour.Equals("X9") || _colour.Equals("R4"))
                                            formattedMsg = formattedMsg.Replace(token.Token.Trim(), token.MessageTrue);
                                    }
                                    formattedMsg = formattedMsg.Replace(token.Token.Trim(), token.MessageFalse.Trim());
                                }
                                break;
                            #endregion
                            case "BENCH!RQ":
                                #region BENCH!RQ
                                if (part.ItemType == "2B")
                                    formattedMsg = formattedMsg.Replace(token.Token.Trim(), token.MessageTrue.Trim());
                                formattedMsg = formattedMsg.Replace(token.Token.Trim(), token.MessageFalse.Trim());
                                break;
                            #endregion
                            case "SKU":
                                #region SKU
                                formattedMsg = formattedMsg.Replace(token.Token.Trim(), item.ItemNumber);
                                break;
                            #endregion
                            case "X9ARM!RQ":
                                #region X9ARM_NOTREQ
                                if (_isRU)
                                {
                                    //TODO:
                                    //formattedMsg = _trimstyle + " " + _colour;
                                }
                                else
                                {
                                    //option 101 - colour
                                    //option 100 - trim style
                                    if ((ItemDetailsFactory.GetOptionValue(part, 101) == "X9" && ItemDetailsFactory.GetOptionValue(part, 100) == "H7") || (ItemDetailsFactory.GetOptionValue(part, 101) == "X9" && ItemDetailsFactory.GetOptionValue(part, 100) == "AL") ||
                                        (ItemDetailsFactory.GetOptionValue(part, 101) == "X9" && ItemDetailsFactory.GetOptionValue(part, 100) == "ML") || (ItemDetailsFactory.GetOptionValue(part, 101) == "X9" && ItemDetailsFactory.GetOptionValue(part, 100) == "TL") ||
                                        (ItemDetailsFactory.GetOptionValue(part, 101) == "X9" && ItemDetailsFactory.GetOptionValue(part, 100) == "JL"))
                                    {
                                        //skip
                                        formattedMsg = formattedMsg.Replace(token.Token.Trim(), token.MessageTrue.Trim());
                                    }
                                    else
                                    {
                                        if ((ItemDetailsFactory.GetOptionValue(part, 101) == "X9" && ItemDetailsFactory.GetOptionValue(part, 100) == "N7") || (ItemDetailsFactory.GetOptionValue(part, 101) == "X9" && ItemDetailsFactory.GetOptionValue(part, 100) == "ZL") ||
                                            (ItemDetailsFactory.GetOptionValue(part, 101) == "X9" && ItemDetailsFactory.GetOptionValue(part, 100) == "CL"))
                                        {
                                            formattedMsg = formattedMsg.Replace(token.Token.Trim(), "(92)");
                                        }
                                    }
                                }
                                formattedMsg = formattedMsg.Replace(token.Token.Trim(), token.MessageFalse.Trim());
                                break;
                            #endregion
                            case "SHLDCLR":
                                #region SHLDCLR
                                if (_isRU)
                                {
                                    //TODO:
                                    //formattedMsg = _trimstyle + " " + _colour;
                                }
                                else
                                {
                                    var _clrshield = _colour;
                                    if (colourExtensions != null)
                                    {
                                        var _ext =
                                            colourExtensions.Where(
                                                cExt =>
                                                cExt.ColourCode == _clrshield && cExt.ExtensionName == "Side Shield").ToList();

                                        if (_ext.Count() > 0)
                                            _clrshield = _ext[0].ColourCodeExt.Trim();
                                    }
                                    formattedMsg = formattedMsg.Replace(token.Token.Trim(), _clrshield);
                                }
                                break;
                            #endregion
                            case "RHD":
                                #region RHD
                                if (_isRU)
                                {
                                    //TODO:
                                    //formattedMsg = _trimstyle + " " + _colour;
                                }
                                else
                                {
                                    //option 2 - lhd/rhd
                                    var _rhd = (ItemDetailsFactory.GetOptionValue(part, 2) == "RHD")
                                                   ? "RHD"
                                                   : String.Empty;
                                    formattedMsg = formattedMsg.Replace(token.Token.Trim(), _rhd);
                                }
                                break;
                            #endregion
                            case "LHPWR":
                                #region LHPWR

                                var _lhpart = item.ItemInfos.Where(i => i.PartIndex == 1).FirstOrDefault();
                                var _rhpart = item.ItemInfos.Where(i => i.PartIndex == 2).FirstOrDefault();

                                if (_isRU)
                                {
                                    var finalStr = string.Empty;
                                    var isLhPwr = (_lhpart.Buildcode & 4) == 4;
                                    var isRhPwr = (_rhpart.Buildcode & 4) == 4;

                                    if (isLhPwr && isRhPwr)
                                        finalStr = "PWR/PWR";
                                    else if (isLhPwr && !isRhPwr)
                                        finalStr = "PWR/MAN %BLD%";
                                    else if (!isLhPwr && !isRhPwr)
                                        finalStr = "MAN/MAN %BLD%";

                                    formattedMsg = formattedMsg.Replace(token.Token.Trim(), finalStr);
                                }
                                else {
                                    if (_lhpart != null)
                                    {
                                        formattedMsg = formattedMsg.Replace(token.Token.Trim(), ((_lhpart.Buildcode & 4) == 4)
                                                                            ? token.MessageTrue
                                                                            : token.MessageFalse);
                                    }
                                }
                                break;
                            #endregion
                            case "RHPWR":
                                #region RHPWR
                                if (_isRU)
                                {
                                    formattedMsg = formattedMsg.Replace(token.Token.Trim(), string.Empty);
                                }
                                else
                                {
                                    var _rhpartA = item.ItemInfos.Where(i => i.PartIndex == 2).FirstOrDefault();
                                    if (_rhpartA != null)
                                    {
                                        formattedMsg = formattedMsg.Replace(token.Token.Trim(), ((_rhpartA.Buildcode & 4) == 4)
                                                                            ? token.MessageTrue
                                                                            : token.MessageFalse);
                                    }
                                }
                                formattedMsg = formattedMsg.Replace(token.Token.Trim(), token.MessageFalse.Trim());
                                break;
                            #endregion
                            case "BCKPNL":
                                #region BCKPNL
                                if (_isRU)
                                {
                                    if (!_trimstyle.Equals("H7"))
                                    {
                                        var _frtRUBackPanel = ItemDetailsFactory.GetOptionValue(part, 102);
                                        formattedMsg = formattedMsg.Replace(token.Token.Trim(), _frtRUBackPanel);
                                    }
                                    formattedMsg = formattedMsg.Replace(token.Token.Trim(), "*Skipped*");
                                }
                                else
                                {
                                    //option 330 back panel part number
                                    //option 101 - colour
                                    var _lhback = "N/A";
                                    var _rhback = "N/A";

                                    if (item.ItemInfos.Where(prt => prt.PartIndex == 1).Count() > 0)
                                        _lhback = ItemDetailsFactory.GetOptionValue(item.ItemInfos.Where(prt => prt.PartIndex == 1).First(), 102);

                                    if (item.ItemInfos.Where(prt => prt.PartIndex == 2).Count() > 0)
                                        _rhback = ItemDetailsFactory.GetOptionValue(item.ItemInfos.Where(prt => prt.PartIndex == 2).First(), 102);

                                    var _back = String.Format("{0}/{1}", _lhback.Trim(), _rhback.Trim());
                                    if (_back.ToUpper().Equals("MESH/MESH") && ItemDetailsFactory.GetOptionValue(part, 101) == "X9")
                                    {
                                        //???
                                        _back += " %LGHT%";
                                    }
                                    formattedMsg = formattedMsg.Replace(token.Token.Trim(), _back);
                                }
                                break;
                            #endregion
                            case "X9PWR!RQ":
                                #region %9PWR_NOTREQ
                                if (_isRU)
                                {
                                    //TODO:
                                    //formattedMsg = _trimstyle + " " + _colour;
                                }
                                else
                                {
                                    //option 101 - colour
                                    if (ItemDetailsFactory.GetOptionValue(part, 101) == "X9" || ItemDetailsFactory.GetOptionValue(part, 101) == "R4")
                                    {
                                        formattedMsg = formattedMsg.Replace(token.Token.Trim(), (((part.Buildcode & token.SeatOptions) ==
                                              (token.SeatOptions & token.SeatOptions2Check)) &&
                                             ((part.Buildcode & token.SeatOptions) ==
                                              (part.Buildcode & token.SeatOptions2Check)))
                                                ? token.MessageTrue.Trim()
                                                : token.MessageFalse.Trim());
                                    }
                                }
                                formattedMsg = formattedMsg.Replace(token.Token.Trim(), token.MessageFalse.Trim());
                                break;
                            #endregion
                            case "X9PASSMAN!RQ":
                                #region X9PASSMAN!RQ
                                if (_isRU)
                                {
                                    //TODO:
                                    //formattedMsg = _trimstyle + " " + _colour;
                                }
                                else
                                {
                                    var _rhpartpassnotreq = item.ItemInfos.Where(i => i.PartIndex == 2).FirstOrDefault();
                                    if (ItemDetailsFactory.GetOptionValue(_rhpartpassnotreq, 101) == "X9")
                                    {
                                        if (ItemDetailsFactory.GetOptionValue(_rhpartpassnotreq, 104) == "MAN")
                                            formattedMsg = formattedMsg.Replace(token.Token.Trim(), token.MessageTrue.Trim());
                                    }
                                }
                                formattedMsg = formattedMsg.Replace(token.Token.Trim(), token.MessageFalse.Trim());
                                break;
                            #endregion
                            case "X9MAN!RQ":
                                #region X9MAN_NOTREQ
                                if (_isRU)
                                {
                                    //TODO:
                                    //formattedMsg = _trimstyle + " " + _colour;
                                }
                                else
                                {
                                    //option 101 - colour
                                    if (ItemDetailsFactory.GetOptionValue(part, 101) == "X9")
                                    {
                                        if (ItemDetailsFactory.GetOptionValue(part, 3) == "MAN")
                                            formattedMsg = formattedMsg.Replace(token.Token.Trim(), token.MessageTrue.Trim());

                                    }
                                }
                                formattedMsg = formattedMsg.Replace(token.Token.Trim(), token.MessageFalse.Trim());
                                break;
                            #endregion
                            case "X9H7RT!RQ":
                                #region X9H7RT_NOTREQ
                                if (_isRU)
                                {
                                    //TODO:
                                    //formattedMsg = _trimstyle + " " + _colour;
                                }
                                else
                                {
                                    //option 101 - colour
                                    //option 100 - trim style
                                    //option 4 - program
                                    //option 9 - BUX
                                    if (ItemDetailsFactory.GetOptionValue(part, 101) == "X9" && ItemDetailsFactory.GetOptionValue(part, 100) == "H7"
                                        && ItemDetailsFactory.GetOptionValue(part, 4) == "RT" && ItemDetailsFactory.GetOptionValue(part, 9) == "")
                                    {
                                        formattedMsg = formattedMsg.Replace(token.Token.Trim(), token.MessageTrue.Trim());
                                    }
                                    else if (ItemDetailsFactory.GetOptionValue(part, 101) == "X9" && ItemDetailsFactory.GetOptionValue(part, 100) == "N7"
                                        && ItemDetailsFactory.GetOptionValue(part, 4) == "RT" && ItemDetailsFactory.GetOptionValue(part, 9) == "")
                                    {
                                        formattedMsg = formattedMsg.Replace(token.Token.Trim(), token.MessageTrue.Trim());
                                    }
                                    else
                                    {
                                        formattedMsg = formattedMsg.Replace(token.Token.Trim(), token.MessageFalse.Trim());
                                    }
                                }
                                break;
                            #endregion
                            case "DRVWIREH":
                                #region DRVWIREH
                                if (_isRU)
                                {
                                    //TODO:
                                    var _wire = ItemDetailsFactory.GetOptionValue(part, 225);
                                    formattedMsg = formattedMsg.Replace(token.Token.Trim(), _wire);
                                }
                                else
                                {
                                    var drvpart = filteredParts.Where(p => p.PartIndex == 1).FirstOrDefault();
                                    if (drvpart != null)
                                    {
                                        var wire = ItemDetailsFactory.GetOptionValue(drvpart, 225);
                                        formattedMsg = formattedMsg.Replace(token.Token.Trim(), wire);
                                        //Adding MEM to 793 and 973 AK


                                        //  if (formattedMsg.Equals(793.ToString()) || formattedMsg.Equals(973.ToString()))  // || formattedMsg.Equals(313.ToString())
                                        //     formattedMsg = formattedMsg + "MEM";
                                    }
                                    else
                                    {
                                        formattedMsg = formattedMsg.Replace(token.Token.Trim(), token.MessageFalse.Trim());
                                    }
                                }
                                break;
                            #endregion
                            case "PASWIREH":
                                #region PASWIREH
                                if (_isRU)
                                {
                                    //TODO:
                                    var _wire = ItemDetailsFactory.GetOptionValue(part, 226);
                                    formattedMsg = formattedMsg.Replace(token.Token.Trim(), _wire);
                                }
                                else
                                {
                                    var paspart = filteredParts.Where(p => p.PartIndex == 2).FirstOrDefault();
                                    if (paspart != null)
                                    {
                                        var wire = ItemDetailsFactory.GetOptionValue(paspart, 225);
                                        formattedMsg = formattedMsg.Replace(token.Token.Trim(), wire);
                                    }
                                    else
                                    {
                                        formattedMsg = formattedMsg.Replace(token.Token.Trim(), token.MessageFalse.Trim());
                                    }
                                }
                                break;
                            #endregion
                            case "RTBUCKLES":
                                #region RTBUCKLES
                                if (_isRU)
                                {
                                    //TODO:
                                    //formattedMsg = _trimstyle + " " + _colour;
                                }
                                else
                                {
                                    var rpart = filteredParts.Where(p => p.PartIndex == 3).FirstOrDefault();
                                    if (rpart != null)
                                    {
                                        var pas = ItemDetailsFactory.GetOptionValue(rpart, 101);
                                        formattedMsg = formattedMsg.Replace(token.Token.Trim(), pas);
                                    }
                                    else
                                        formattedMsg = formattedMsg.Replace(token.Token.Trim(), token.MessageFalse.Trim());
                                }
                                break;
                            #endregion
                            case "SEATBELT":
                                #region SEATBELT
                                if (_isRU)  //OP1100N
                                {
                                    formattedMsg = formattedMsg.Replace(token.Token.Trim(), "*Skipped*");
                                }
                                else
                                {
                                    var spart = filteredParts.Where(p => p.PartIndex == 1).FirstOrDefault();
                                    if (spart != null)
                                    {
                                        var pas2 = ItemDetailsFactory.GetOptionValue(spart, 420);
                                        var pas = "";
                                        if (pas2 != "")
                                        {
                                            pas = pas2.Substring(pas2.Length - 2) + "-" + pas2.Substring(0, 2);
                                            if (spart.ItemDescription.Contains("MAN"))
                                                pas = pas + "-<span style=\"color: blue;\">MAN</span>";
                                            else if (spart.ItemDescription.Contains("PWR"))
                                                pas = pas + "-<span style=\"color: #FF6600;\">PWR</span>";
                                        }
                                        formattedMsg = pas; // formattedMsg.Replace(token.Token.Trim(), pas);
                                    }
                                    else
                                        formattedMsg = formattedMsg.Replace(token.Token.Trim(), token.MessageFalse.Trim());
                                }
                                break;
                            #endregion
                            case "PASSEATBELT":
                                #region PASSEATBELT
                                if (_isRU)
                                {
                                    var ruSeatBeltPartno = ItemDetailsFactory.GetOptionValue(part, 270);
                                    var msg = ruSeatBeltPartno;
                                    if (ruSeatBeltPartno.Length > 4)
                                        msg = ruSeatBeltPartno.Substring(ruSeatBeltPartno.Length - 4) + " (2)";

                                    formattedMsg = formattedMsg.Replace(token.Token.Trim(), msg);
                                }
                                else
                                {
                                    var seatpart = filteredParts.Where(p => p.PartIndex == 2).FirstOrDefault();
                                    if (seatpart != null)
                                    {
                                        var pas2 = ItemDetailsFactory.GetOptionValue(seatpart, 420);
                                        var pas = "";
                                        if (pas2 != "")
                                        {
                                            pas = pas2.Substring(pas2.Length - 2) + "-" + pas2.Substring(0, 2);
                                            if (seatpart.ItemDescription.Contains("MAN"))
                                                pas = pas + "-<span style=\"color: blue;\">MAN</span>";
                                            else if (seatpart.ItemDescription.Contains("PWR"))
                                                pas = pas + "-<span style=\"color: #FF6600;\">PWR</span>";
                                        }
                                        formattedMsg = pas; // formattedMsg.Replace(token.Token.Trim(), pas);
                                    }
                                    else
                                    {
                                        formattedMsg = formattedMsg.Replace(token.Token.Trim(), token.MessageFalse.Trim());
                                    }
                                }
                                break;
                            #endregion

                            default:
                                #region DEFAULT
                                formattedMsg = formattedMsg.Replace(token.Token.Trim(), (((part.Buildcode & token.SeatOptions) ==
                                                                  (token.SeatOptions & token.SeatOptions2Check)) &&
                                                                 ((part.Buildcode & token.SeatOptions) ==
                                                                  (part.Buildcode & token.SeatOptions2Check)))
                                                                    ? token.MessageTrue.Trim()
                                                                   : token.MessageFalse.Trim());
                                #endregion
                                break;
                        }
                    }

                    return formattedMsg;
                }
            }

            return String.Format("*Skipped* ({0})", itemNumber);
        }
        private void UpdateNextSeqScheduleSideBySide(SequencingStation station, List<SideBySide> buffer, int side)
        {
            SequencingFactory factory = new SequencingFactory();
            var seqMessageProcessor = new SeqMessageProcessor();

            var tokens = MessageTokensCacheManager.MessageTokens.Where(t => t.LineId == station.Line.Id).ToList();

            var itemsinbox = station.PartsPerBox;
            var boxperschedule = station.BoxPerSchedule;
            var itemsinschedule = itemsinbox * boxperschedule;

            SideBySide firstItem = null;
            if (side ==1)
                firstItem = buffer.Where(s => s.Complete1 == false).OrderBy(s => s.OrderId).FirstOrDefault();
            else
                firstItem = buffer.Where(s => s.Complete2 == false).OrderBy(s => s.OrderId).FirstOrDefault();

            if (firstItem != null)
            {
                if(side == 1)
                    firstItem.StartDrawSchedule1 = true;
                else
                    firstItem.StartDrawSchedule2 = true;

                var currentBox = station.NextBox.BoxNum;
                var jobs = buffer.Where(s => s.OrderId >= firstItem.OrderId).OrderBy(s => s.OrderId).Take(itemsinschedule).ToList();

                var itemsinscheduleTmp = itemsinschedule;
                var itemsinboxTmp = itemsinbox;
                var boxesperscheduleTmp = boxperschedule;

                foreach (var j in jobs)
                {
                    if (side == 1)
                    {
                        j.ScheduleNum1 = station.NextBox.ScheduleNum;
                        j.ScheduleCount1 = itemsinschedule;
                        j.StartDrawBox1 = true;
                        j.BoxNum1 = currentBox;
                    }
                    else
                    {
                        j.ScheduleNum2 = station.NextBox.ScheduleNum;
                        j.ScheduleCount2 = itemsinschedule;
                        j.StartDrawBox2 = true;
                        j.BoxNum2 = currentBox;
                    }

                    var message = seqMessageProcessor.GetSequencingMessage(station, j.ItemNumber, tokens).Trim();

                    if (message.ToUpper().IndexOf("*SKIPPED*") < 0)
                        --itemsinboxTmp;

                    --itemsinscheduleTmp;

                    if (itemsinboxTmp > 0 && itemsinscheduleTmp > 0) continue;
                    if (itemsinschedule <= 0)
                        break;

                    itemsinboxTmp = station.PartsPerBox;
                    --boxesperscheduleTmp;

                    if (side == 1)
                        j.StartDrawBox1 = false;
                    else
                        j.StartDrawBox2 = false;

                    if (currentBox + 1 > station.BoxQty)
                        currentBox = 1;
                    else
                    {
                        currentBox++;
                    }

                }

                

            }
        }
        private void SetScheduleAvailable(SequencingStation station, int validCount)
        {
            var jobsRequired = station.PartsPerBox * station.BoxPerSchedule;

            station.ItemsWaiting = jobsRequired - validCount;

            if (station.ItemsWaiting <= 0)
            {
                station.ScheduleAvailable = true;
                station.ItemsWaiting = 0;
                station.ItemsWaitingPercentage = 100;
            }
            else
            {
                station.ScheduleAvailable = false;
                station.ItemsWaitingPercentage = (int)((100f * (validCount)) / jobsRequired);
                if (station.ItemsWaitingPercentage >= 100)
                    station.ItemsWaitingPercentage = 99;
            }
        }
        public void CompletePlasticSeqByStation(SequencingStation station)
        {
            #region Complete Plastic Seq By Station
            PartSequencingDataContext dbSeq = new PartSequencingDataContext();
            HP_MESDataContext dbMes = new HP_MESDataContext();
            SequencingFactory seqFactory = new SequencingFactory();
            var seqMessageProcessor = new SeqMessageProcessor();

            var completeDTM = DateTime.Now;

            var lineBuffer = seqFactory.GetSequencingBuffer(station);

            if (station.ScheduleAvailable)
            {
                Log.Logging.Info("station.ScheduleAvailable = true|Seq Id: {0}", station.Id);

                var itemsinbox = station.PartsPerBox;
                var boxperschedule = station.BoxPerSchedule;
                var itemsinschedule = itemsinbox * boxperschedule;

                var currentBox = station.NextBox.BoxNum;

                var jobs = lineBuffer.Where(i => i.OrderId >= station.NextBox.OrderId).Take(itemsinschedule).ToList();
                Log.Logging.Info("Job Count: {0}|Station: {1} Seq Id: {2}", jobs.Count(), station.SequencingLocation.Description, station.Id);
                var tokens = MessageTokensCacheManager.MessageTokens.Where(t => t.LineId == station.Line.Id).ToList();

                SequencingTrackingHistoryDetail histDetail = new SequencingTrackingHistoryDetail
                {
                    BoxNum = currentBox,
                    DTM = completeDTM,
                    ScheduleNum = station.NextBox.ScheduleNum,
                    SequencingStationSettingsId = station.Id,
                    Type = 1
                };

                dbSeq.SequencingTrackingHistoryDetails.InsertOnSubmit(histDetail);
                dbSeq.SubmitChanges();

                Log.Logging.Info("History Header|BoxNum={0}, DTM={1}, ScheduleNum={2}, SeqId={3}, Type={4}", histDetail.BoxNum, histDetail.DTM, histDetail.ScheduleNum, histDetail.SequencingStationSettingsId, histDetail.Type);

                int position = 1;
                foreach (var job in jobs)
                {
                    var message = seqMessageProcessor.GetSequencingMessage(station, job.ItemNumber, tokens).Trim();

                    SequencingTrackingHistory hist = new SequencingTrackingHistory
                    {
                        OrderNumber = job.OrderNumber,
                        ItemNumber = job.ItemNumber,
                        ItemType = job.ItemType,
                        JobId = job.JobId,
                        Position = position,
                        OrderId = job.OrderId,
                        SequencingTrackingHistoryDetail = histDetail,
                    };
                    position++;

                    dbSeq.SequencingTrackingHistories.InsertOnSubmit(hist);

                    Log.Logging.Info("History Detail Item|Job Hist = {0}|Station: {1} Seq Id: {2}", hist, station.SequencingLocation.Description, station.Id);
                    Log.Logging.Info("History Detail Item|OrderNumber={0}, ItemNumber={1}, ItemType={2}, JobId={3}, Position={4}, OrderId={5}", hist.OrderNumber, hist.ItemNumber, hist.ItemType, hist.JobId, hist.Position, hist.OrderId);

                    dbSeq.SubmitChanges();

                    if (message.ToUpper().IndexOf("*SKIPPED*") < 0)
                        --itemsinbox;

                    --itemsinschedule;

                    if (itemsinbox > 0 && itemsinschedule > 0) continue;
                    if (itemsinschedule <= 0)
                        break;

                    itemsinbox = station.PartsPerBox;
                    --boxperschedule;

                    if (currentBox + 1 > station.BoxQty)
                        currentBox = 1;
                    else
                    {
                        currentBox++;
                        position = 1;
                    }

                    histDetail = new SequencingTrackingHistoryDetail
                    {
                        Type = 1,
                        BoxNum = currentBox,
                        DTM = completeDTM,
                        ScheduleNum = station.NextBox.ScheduleNum,
                        SequencingStationSettingsId = station.Id,
                    };

                    Log.Logging.Info("History Detail|BoxNum={0}, DTM={1}, ScheduleNum={2}, SeqId={3}, Type={4}", histDetail.BoxNum, histDetail.DTM, histDetail.ScheduleNum, histDetail.SequencingStationSettingsId, histDetail.Type);

                }


                var lookup = dbSeq.SequencingStationLookups.Where(s => s.SequenceStationSettingsId == station.Id).FirstOrDefault();
                if (lookup != null)
                {
                    if (jobs.Count() > 0)
                    {
                        Log.Logging.Info("Count Jobs={0} SeqId={1}", jobs.Count(), station.Id);
                        var lastJob = jobs.Last();
                        if (lastJob != null)
                        {
                            Log.Logging.Info("Last Jobs: OrderId={0} SeqId={1}", lastJob.OrderId, station.Id);
                            lookup.NextOrderId = lastJob.OrderId + 1;
                            dbSeq.SubmitChanges();
                            Log.Logging.Info("Success Update Lookup: NextOrderId={0} NextScheduleNum={1} NextNextBoxNum={2}", lookup.NextOrderId, lookup.NextScheduleNum, lookup.NextBoxNum);
                        }
                    }
                }

            }
            else
            {
                Log.Logging.Info("station.ScheduleAvailable = false|Seq Id: {0}", station.Id);
            }
            #endregion
        }
        public PlasticSeqSchedule GetPlasticSeqScheduleHistoryDetail(SequencingStation station, int scheduleNum)
        {
            #region Get Plastic Seq Schedule History Detail
            PartSequencingDataContext dbSeq = new PartSequencingDataContext();
            SequencingFactory factory = new SequencingFactory();
            PlasticSeqSchedule plasticHistorySchedule = new PlasticSeqSchedule();
            var seqMessageProcessor = new SeqMessageProcessor();

            var tokens = MessageTokensCacheManager.MessageTokens.Where(t => t.LineId == station.Line.Id || t.LineId == 4).ToList();

            var boxHistory = (from h in dbSeq.IWS_GetSequencingDetailHistoryBySeqSettingsIdAndScheduleNum(station.Id, scheduleNum)
                              group h by new
                              {
                                  h.ScheduleNum,
                                  h.BoxNum
                              } into grp
                              select new ScheduleBox
                              {
                                  BoxNum = grp.Key.BoxNum,
                                  Items = (from s in grp.ToList()
                                           select new ScheduleItem
                                           {
                                               Message = seqMessageProcessor.GetSequencingMessage(station, s.ItemNumber.Trim(), tokens),
                                               Position = (int)s.Position
                                           }).ToList(),
                              }).ToList();

            plasticHistorySchedule = new PlasticSeqSchedule
            {
                SequencingStation = station,
                Boxes = boxHistory,
                Status = true,
            };

            return plasticHistorySchedule;
            #endregion
        }