public bool IsScheduleReadyBySequencingStationId(int id)
        {
            PartSequencingDataContext dbSeq = new PartSequencingDataContext();
            SequencingScheduleFactory maker = new SequencingScheduleFactory();
            MesDataContext dbMes = new MesDataContext();

            var seqStations = dbSeq.SequencingStationSettings.Where(i => i.SequencingLocationId == id).ToList();
            if (seqStations.Count() > 0)
            {
                var seqStation = seqStations.FirstOrDefault();
                if (seqStation != null)
                {
                    var station = maker.UpdateNextBoxBySequencingId(seqStation.Id);
                    if (!station.Status)
                    {
                        if (station.ItemsWaiting != 0)
                            return false;
                    }
                    
                    var scheduleStatus = dbSeq.SequencingStationLookups.Where(s => s.SequenceStationSettingsId == station.Id).FirstOrDefault();
                    var tokens = MessageTokensCacheManager.MessageTokens.Where(s => s.LineId == station.Line.Id || s.LineId == 4).ToList();

                    var lineBuffer = maker.GetSequencingBuffer(station);

                    SequencingTrackingItem lastItem = null;
                    var tracking = maker.GetSequencingHistory(station);

                    if (tracking.Any())
                        lastItem = tracking.OrderByDescending(i => i.OrderId).First();

                    var lastJobId = Int32.MinValue;

                    if (lastItem != null)
                        lastJobId = lastItem.OrderId;

                    if (lineBuffer != null)
                    {
                        var itemsinbox = station.PartsPerBox;
                        var boxperschedule = station.BoxPerSchedule;
                        var itemsinschedule = itemsinbox * boxperschedule;

                        var jobs = lineBuffer.Where(i => i.OrderId >= station.NextBox.OrderId).Take(itemsinschedule).ToList();
                        if (itemsinschedule == jobs.Count())
                            return true;
                    }
                }
            }

            return false;
        }
        public TrimScheduleInfo TrimPreviousScheduleHistoryDetail(int locationId)
        {
            SequencingScheduleFactory factory = new SequencingScheduleFactory();
            TrimScheduleFactory trimFactory = new TrimScheduleFactory();
            var histories = factory.GetScheduleHistory(locationId);
            var lastHistory = histories.FirstOrDefault();
            if (lastHistory != null)
            {
                var schedule = trimFactory.GetTrimScheduleHistoryDetail(locationId, (int)lastHistory.ScheduleNum);
                if (schedule == null)
                {
                    throw new HttpResponseException(
                          HttpErrorResponse.GetHttpErrorResponse(
                          HttpStatusCode.NotFound, "Trim Previous Schedule Not Available", string.Format("Trim Previous Schedule With Aisle ID = {0} does not exist", locationId)));
                }
                return schedule;
            
            }

            throw new HttpResponseException(
                          HttpErrorResponse.GetHttpErrorResponse(
                          HttpStatusCode.NotFound, "Trim Previous Schedule Not Available", string.Format("Trim Previous Schedule With Aisle ID = {0} does not exist", locationId)));
        }
        public IEnumerable<SideBySide> GetSequencingTracking2StationsByLineId(int lineId, int seqId1, int seqId2)
        {
            MesDataContext dbMes = new MesDataContext();
            SequencingScheduleFactory factory = new SequencingScheduleFactory();

            var results = (from s in dbMes.IWS_SP_GetWIPSequencingTracking2StationsByLineId(lineId, seqId1, seqId2)
                           select new SideBySide
                           {
                               Complete1 = s.ScheduleNum1 == -1 ? false : true,
                               Complete2 = s.ScheduleNum2 == -1 ? false : true,
                               BoxNum1 = s.BoxNum1,
                               BoxNum2 = s.BoxNum2,
                               Group = s.Group,
                               ItemNumber = s.ItemNumber,
                               ItemType = s.ItemType,
                               JobId = (int)s.JobId,
                               LineId = (int)s.LineId,
                               OrderId = (int)s.OrderId,
                               OrderStatus = (int)s.OrderStatus,
                               OrderNumber = s.OrderNumber,
                               Position1 = s.Position1,
                               Position2 = s.Position2,
                               Region = s.Region,
                               ScheduleNum1 = s.ScheduleNum1,
                               ScheduleNum2 = s.ScheduleNum2,
                               Type1 = s.Type1,
                               Type2 = s.Type2,
                           }).ToList();

            var station1 = factory.UpdateNextBoxBySequencingId(seqId1);
            var station2 = factory.UpdateNextBoxBySequencingId(seqId2);

            UpdateNextSeqScheduleSideBySide(station1, results, 1);
            UpdateNextSeqScheduleSideBySide(station2, results, 2);


            var scheduleNum1 = -1;
            var scheduleNum2 = -1;
            var boxNum1 = -1;
            var boxNum2 = -1;

            var itemsinschedule1 = station1.PartsPerBox * station1.BoxPerSchedule;
            var itemsinschedule2 = station2.PartsPerBox * station2.BoxPerSchedule;

            //Schedule calc
            for (var i = 0; i < results.Count(); i++)
            {

                if (results[i].ScheduleNum1 != scheduleNum1)
                {

                    results[i].StartDrawSchedule1 = true;

                    var countSchedule = 0;
                    for (var j = i; j < results.Count(); j++)
                    {
                        if (results[j].ScheduleNum1 == results[i].ScheduleNum1)
                        {
                            countSchedule++;
                        }
                        else
                        {
                            break;
                        }
                    }

                    if (results[i].Complete1)
                        results[i].ScheduleCount1 = countSchedule;
                    else
                    {
                        if (countSchedule > itemsinschedule1)
                            results[i].ScheduleCount1 = itemsinschedule1;
                        else
                            results[i].ScheduleCount1 = countSchedule;
                    }

                    scheduleNum1 = results[i].ScheduleNum1;
                }
                else
                {
                    results[i].StartDrawSchedule1 = false;
                }

                if (results[i].ScheduleNum2 != scheduleNum2)
                {

                    results[i].StartDrawSchedule2 = true;

                    var countSchedule = 0;
                    for (var j = i; j < results.Count(); j++)
                    {
                        if (results[j].ScheduleNum2 == results[i].ScheduleNum2)
                        {
                            countSchedule++;
                        }
                        else
                        {
                            break;
                        }
                    }

                    if (results[i].Complete2)
                        results[i].ScheduleCount2 = countSchedule;
                    else
                    {
                        if (countSchedule > itemsinschedule2)
                            results[i].ScheduleCount2 = itemsinschedule2;
                        else
                            results[i].ScheduleCount2 = countSchedule;
                    }

                    scheduleNum2 = results[i].ScheduleNum2;
                }
                else
                {
                    results[i].StartDrawSchedule2 = false;
                }


            }

            //Box Calc
            scheduleNum1 = -1;
            scheduleNum2 = -1;
            for (var i = 0; i < results.Count(); i++)
            {
                if (results[i].BoxNum1 != boxNum1 || results[i].ScheduleNum1 != scheduleNum1)
                {
                    results[i].StartDrawBox1 = true;

                    var countBox = 0;

                    for (var j = i; j < results.Count(); j++)
                    {
                        if (results[j].BoxNum1 == results[i].BoxNum1 && results[j].ScheduleNum1 == results[i].ScheduleNum1)
                        {
                            countBox++;
                        }

                    }
                    results[i].BoxCount1 = countBox;

                    boxNum1 = results[i].BoxNum1;
                    scheduleNum1 = results[i].ScheduleNum1;

                }
                else
                {
                    results[i].StartDrawBox1 = false;
                }

                if (results[i].BoxNum2 != boxNum2 || results[i].ScheduleNum2 != scheduleNum2)
                {
                    results[i].StartDrawBox2 = true;

                    var countBox = 0;

                    for (var j = i; j < results.Count(); j++)
                    {
                        if (results[j].BoxNum2 == results[i].BoxNum2 && results[j].ScheduleNum2 == results[i].ScheduleNum2)
                        {
                            countBox++;
                        }

                    }
                    results[i].BoxCount2 = countBox;

                    boxNum2 = results[i].BoxNum2;
                    scheduleNum2 = results[i].ScheduleNum2;

                }
                else
                {
                    results[i].StartDrawBox2 = false;
                }
            }



            return results;
        }
        private void UpdateNextSeqScheduleSideBySide(SequencingStation station, List<SideBySide> buffer, int side)
        {
            SequencingScheduleFactory factory = new SequencingScheduleFactory();
            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 = factory.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++;
                    }

                }

                

            }
        }
        public HttpResponseMessage CompleteSeqStationSchedule(int seqId)
        {
            SequencingScheduleFactory maker = new SequencingScheduleFactory();
            maker.CompleteSequencingStation(seqId);

            return new HttpResponseMessage(HttpStatusCode.OK);
        }
 public SideBySideStatistics GetStationOffset2Stations(int lineId, int seqId1, int seqId2)
 {
     SequencingScheduleFactory factory = new SequencingScheduleFactory();
     var stat = factory.GetSideBySideStatistics(lineId, seqId1, seqId2);
     return stat;
 }
        public HttpResponseException TrimScheduleReady(int id)
        {
            SequencingScheduleFactory seqFactory = new SequencingScheduleFactory();
            TrimScheduleFactory trimFactory = new TrimScheduleFactory();
            var ready = trimFactory.IsScheduleReadyBySequencingStationId(id);
            if (ready)
            {
                return new HttpResponseException(HttpStatusCode.OK);
            }
            else
            {
                throw new HttpResponseException(
                          HttpErrorResponse.GetHttpErrorResponse(
                          HttpStatusCode.NotFound, "Trim Schedule Not Available", string.Format("Trim Schedule With Aisle ID = {0} does not exist", id)));
            }

        }
        public void CompleteTrimSchedule(TrimScheduleInfo schedule, int id, int employeeId)
        {
            PartSequencingDataContext dbSeq = new PartSequencingDataContext();
            EmployeeDatabase dbEmp = new EmployeeDatabase();
            SequencingScheduleFactory factory = new SequencingScheduleFactory();

            var employee = dbEmp.GetEmployeeInfo(employeeId);
            var seqStations = dbSeq.SequencingStationSettings.Where(i => i.SequencingLocationId == id).ToList();

            if (seqStations.Count() > 0)
            {
                var seqStation = seqStations.FirstOrDefault();
                if (seqStation != null)
                {
                    var station = factory.UpdateNextBoxBySequencingId(seqStation.Id);
                    var statusLookup = dbSeq.SequencingStationLookups.Where(i => i.SequenceStationSettingsId == seqStation.Id).FirstOrDefault();

                    int boxNum = schedule.ScheduleStatus.CurrentBoxNumber;
                    int scheduleNum = schedule.ScheduleStatus.CurrentScheduleNumber;

                    //check if job completed already
                    bool isComplete = false;
                    var isCompleteResult = dbSeq.IsSequencingScheduleComplete(seqStation.Id, boxNum, scheduleNum);
                    if (isCompleteResult.HasValue == true) // it's null
                        isComplete = (bool)isCompleteResult;

                    if (isComplete)
                    {
                        throw new HttpResponseException(
                            HttpErrorResponse.GetHttpErrorResponse(
                            HttpStatusCode.NotFound, "Trim Schedule Already Completed", string.Format("Trim Schedule {0} Already Completed", scheduleNum)));
                    }

                    if (schedule.ScheduleStatus.CurrentBoxNumber == statusLookup.NextBoxNum
                        && schedule.ScheduleStatus.CurrentScheduleNumber == statusLookup.NextScheduleNum)
                    {
                        var lastjob = schedule.SeatSchedule.Last();
                        var firstjob = schedule.SeatSchedule.First();

                        //get schedule parameters by station
                        var itemsinbox = station.PartsPerBox;
                        var boxperschedule = station.BoxPerSchedule;
                        var itemsinschedule = itemsinbox * boxperschedule;

                        //get sequencing buffer
                        var lineBuffer = factory.GetSequencingBuffer(station);
                        //filter sequencing buffer by last job and first job
                        var validBuffer = lineBuffer.Where(i => i.OrderId <= lastjob.OrderId && i.OrderId >= firstjob.OrderId).OrderBy(s => s.OrderId).ToList();

                        if (validBuffer.Count() == itemsinschedule) //check if there is enough seats to fulfill schedule
                        {
                            if (schedule.OffsetSeats != null)
                            {
                                if (schedule.OffsetSeats.Count() > 0)
                                {

                                }
                            }


                            //save history
                            SequencingTrackingHistoryDetail histDetail = new SequencingTrackingHistoryDetail
                            {
                                BoxNum = schedule.ScheduleStatus.CurrentBoxNumber,
                                DTM = DateTime.Now,
                                ScheduleNum = schedule.ScheduleStatus.CurrentScheduleNumber,
                                SequencingStationSettingsId = station.Id,
                                Type = 1
                            };
                            dbSeq.SequencingTrackingHistoryDetails.InsertOnSubmit(histDetail);

                            foreach (var seat in schedule.SeatSchedule)
                            {
                                SequencingTrackingHistory hist = new SequencingTrackingHistory
                                {
                                    Position = seat.Index + 1,
                                    OrderId = seat.OrderId,
                                    ItemNumber = seat.ItemNumber,
                                    OrderNumber = seat.OrderNumber,
                                    ItemType = seat.ItemType,
                                    JobId = seat.JobId,
                                    SequencingTrackingHistoryDetail = histDetail,
                                };

                                dbSeq.SequencingTrackingHistories.InsertOnSubmit(hist);
                            }

                            //queue station items
                            if ((bool)station.SequencingLocation.QueueItems)
                            {
                                var queueStations = dbSeq.SequencingLocations.Where(l => l.ParentId == station.SequencingLocation.Id).ToList();

                                if (queueStations.Count() > 0)
                                {
                                    foreach (var st in queueStations)
                                    {
                                        var queueItems = (from s in schedule.SeatSchedule
                                                          select new SequencingStationQueue
                                                          {
                                                              OrderNumber = s.OrderNumber == null ? "" : s.OrderNumber.Trim(),
                                                              BoxNum = schedule.ScheduleStatus.CurrentBoxNumber,
                                                              InsertedDTM = DateTime.Now,
                                                              UpdatedDTM = DateTime.Now,
                                                              ItemNumber = s.ItemNumber.Trim(),
                                                              ItemType = s.ItemType.Trim(),
                                                              JobId = s.JobId,
                                                              OrderId = s.OrderId,
                                                              Region = "",
                                                              ScheduleNum = schedule.ScheduleStatus.CurrentScheduleNumber,
                                                              SequencingLocationId = st.Id,
                                                              OrderStatus = (byte)s.OrderStatus,
                                                          }).ToList();

                                        dbSeq.SequencingStationQueues.InsertAllOnSubmit(queueItems);
                                        dbSeq.SubmitChanges();
                                    }
                                }
                            }

                            //no parent station delete from the queue table
                            if (station.SequencingLocation.ParentId != null)
                            {
                                var deleteSeats = dbSeq.SequencingStationQueues.Where(i => i.OrderId <= lastjob.OrderId && i.OrderId >= firstjob.OrderId && i.SequencingLocationId == station.SequencingLocation.Id).OrderBy(s => s.OrderId).ToList();
                                dbSeq.SequencingStationQueues.DeleteAllOnSubmit(deleteSeats);
                                dbSeq.SubmitChanges();
                            }

                            var scheduleHist = new SequencingStationScheduleHistory
                            {
                                EmployeeId = employeeId,
                                EmployeeName = employee == null ? "Unknown Employee" : employee.Name.Trim(),
                                ScheduleNum = schedule.ScheduleStatus.CurrentScheduleNumber,
                                SequencingLocationId = id,
                                DateCompleted = DateTime.Now,
                            };
                            dbSeq.SequencingStationScheduleHistories.InsertOnSubmit(scheduleHist);

                            var nextjob = lineBuffer.Where(i => i.OrderId > lastjob.OrderId).OrderBy(s => s.OrderId).FirstOrDefault();
                            statusLookup.NextBoxNum = schedule.ScheduleStatus.CurrentBoxNumber + 1;
                            statusLookup.NextOrderId = nextjob == null ? statusLookup.NextOrderId + 1 : nextjob.OrderId;
                            statusLookup.NextScheduleNum = schedule.ScheduleStatus.CurrentScheduleNumber + 1;
                            
                            dbSeq.SubmitChanges();

                            //if (id == 7) //first row complete schedule
                            //{
                            //    CompleteTrimSchedule(schedule, 8, employeeId);
                            //}
                        }
                    }
                }
            }
        }
        public TrimSchedule GetTrimSchedule(int id)
        {
            PartSequencingDataContext dbSeq = new PartSequencingDataContext();
            SequencingScheduleFactory factory = new SequencingScheduleFactory();
            MesDataContext dbMes = new MesDataContext();
            ItemDetailsModel itemDetailsModel = new ItemDetailsModel();
            TrimSchedule trimSchedule = null;
            List<Seat> offsetSeats = null;
            List<Seat> currentjobs = null;

            var seqStations = dbSeq.SequencingStationSettings.Where(i => i.SequencingLocationId == id).ToList();
            if (seqStations.Count() > 0)
            {
                var seqStation = seqStations.FirstOrDefault();
                if (seqStation != null)
                {
                    var station = factory.UpdateNextBoxBySequencingId(seqStation.Id);
                    var scheduleStatus = dbSeq.SequencingStationLookups.Where(s => s.SequenceStationSettingsId == station.Id).FirstOrDefault();
                    var tokens = MessageTokensCacheManager.MessageTokens.Where(s => s.LineId == station.Line.Id || s.LineId == 4).ToList();

                    var lineBuffer = factory.GetSequencingBuffer(station);

                    if (lineBuffer != null)
                    {
                        var itemsinbox = station.PartsPerBox;
                        var boxperschedule = station.BoxPerSchedule;
                        var itemsinschedule = itemsinbox * boxperschedule;
                        var boxqty = station.BoxQty;

                        trimSchedule = new TrimSchedule
                        {

                        };


                        //trimSchedule.PreviousSchedule = new TrimScheduleInfo();

                        //SequencingTrackingItem lastItem = null;
                        //var tracking = factory.GetSequencingHistory(station);

                        //if (tracking.Any())
                        //{
                        //    lastItem = tracking.OrderByDescending(i => i.OrderId).First();
                        //    if (lastItem != null)
                        //    {
                        //        int previousScheduleNum = lastItem.ScheduleNum;
                        //        var previousjobs = (from t in tracking.Where(i=>i.ScheduleNum == previousScheduleNum)
                        //                           select new Seat {
                        //                               OrderNumber = t.OrderNumber,
                        //                               OrderStatus = t.OrderStatus,
                        //                               Complete = false,
                        //                               TrimStyle = GetOptionValue(t.ItemNumber.Trim(), 100),
                        //                               Colour = GetOptionValue(t.ItemNumber.Trim(), 101),
                        //                               ItemNumber = t.ItemNumber.Trim(),
                        //                               ItemType = t.ItemType.Trim(),
                        //                               DescLine1 = t.ItemNumber.Trim(),
                        //                               DescLine2 = factory.GetSequencingMessage(station, t.ItemNumber.Trim(), tokens),
                        //                               JobId = (int)t.JobId,
                        //                               OrderId = t.OrderId,
                        //                               Item = itemDetailsModel.GetItemInfoByLineId(t.ItemNumber.Trim(), station.Line.Id)
                        //                           }).ToList();
                        //        trimSchedule.PreviousSchedule.SeatSchedule = previousjobs;
                        //        trimSchedule.PreviousSchedule.SummaryList = GetSummaryHeaderItems(previousjobs, station.Line.Id);
                        //        trimSchedule.PreviousSchedule.ScheduleStatus = new TrimScheduleStatus
                        //        {
                        //            CurrentBoxNumber = lastItem.BoxNum,
                        //            CurrentScheduleNumber = lastItem.ScheduleNum
                        //        };
                        //    }

                        //}
                        //else
                        //{
                        //    trimSchedule.PreviousSchedule = null;
                        //}
                        var tracking = factory.GetSequencingHistory(station);
                        if (tracking.Any()) 
                        {
                            var lastTrackItem = tracking.LastOrDefault();
                            if (lastTrackItem != null)
                            {
                                if (lastTrackItem.Type == 2)
                                {
                                    var lastRealJob = tracking.Where(o => o.OrderId < lastTrackItem.OrderId).OrderByDescending(f => f.OrderId).Where(x => x.ScheduleNum > 0).FirstOrDefault();

                                    if (lastRealJob != null)
                                    {
                                        var unassignedBuffer = tracking.Where(o => o.OrderId <= lastTrackItem.OrderId && o.OrderId >lastRealJob.OrderId).OrderBy(f => f.OrderId).ToList();
                                        if (unassignedBuffer.Count() > 0)
                                        {
                                            var offsetjobs = (from j in unassignedBuffer
                                                              select new Seat
                                                              {
                                                                  OrderStatus = (int)j.OrderStatus,
                                                                  Complete = false,
                                                                  TrimStyle = GetOptionValue(j.ItemNumber.Trim(), 100),
                                                                  Colour = GetOptionValue(j.ItemNumber.Trim(), 101),
                                                                  OrderNumber = j.OrderNumber == null ? "" : j.OrderNumber.Trim(),
                                                                  ItemNumber = j.ItemNumber.Trim(),
                                                                  ItemType = j.ItemType.Trim(),
                                                                  DescLine1 = j.ItemNumber.Trim(),
                                                                  DescLine2 = factory.GetSequencingMessage(station, j.ItemNumber.Trim(), tokens),
                                                                  JobId = (int)j.JobId,
                                                                  OrderId = j.OrderId,
                                                                  Item = itemDetailsModel.GetItemInfoByLineId(j.ItemNumber.Trim(), station.Line.Id)
                                                              }).ToList();

                                            offsetSeats = offsetjobs;
                                        }
                                    }

                                }
                            }


                        }


                        if (station.SequencingLocation.ParentId == null)
                        {
                            currentjobs = (from j in lineBuffer.Where(i => i.OrderId >= station.NextBox.OrderId).Take(itemsinschedule).ToList()
                                           select new Seat
                                           {
                                               OrderStatus = (int)j.OrderStatus,
                                               Complete = false,
                                               TrimStyle = GetOptionValue(j.ItemNumber.Trim(), 100),
                                               Colour = GetOptionValue(j.ItemNumber.Trim(), 101),
                                               OrderNumber = j.OrderNumber == null ? "" : j.OrderNumber.Trim(),
                                               ItemNumber = j.ItemNumber.Trim(),
                                               ItemType = j.ItemType.Trim(),
                                               DescLine1 = j.ItemNumber.Trim(),
                                               DescLine2 = factory.GetSequencingMessage(station, j.ItemNumber.Trim(), tokens),
                                               JobId = (int)j.JobId,
                                               OrderId = j.OrderId,
                                               Item = itemDetailsModel.GetItemInfoByLineId(j.ItemNumber.Trim(), station.Line.Id),
                                           }).OrderBy(s => s.OrderId).ToList();
                        }
                        else //from queue
                        {
                            currentjobs = (from j in lineBuffer.Where(i => i.OrderId >= station.NextBox.OrderId).Take(itemsinschedule).ToList()
                                            select new Seat
                                            {
                                                ScheduleNum = j.ScheduleNum,
                                                BoxNum = j.BoxNum,
                                                OrderStatus = (int)j.OrderStatus,
                                                Complete = false,
                                                TrimStyle = GetOptionValue(j.ItemNumber.Trim(), 100),
                                                Colour = GetOptionValue(j.ItemNumber.Trim(), 101),
                                                OrderNumber = j.OrderNumber == null ? "" : j.OrderNumber.Trim(),
                                                ItemNumber = j.ItemNumber.Trim(),
                                                ItemType = j.ItemType.Trim(),
                                                DescLine1 = j.ItemNumber.Trim(),
                                                DescLine2 = factory.GetSequencingMessage(station, j.ItemNumber.Trim(), tokens),
                                                JobId = (int)j.JobId,
                                                OrderId = j.OrderId,
                                                Item = itemDetailsModel.GetItemInfoByLineId(j.ItemNumber.Trim(), station.Line.Id),
                                            }).OrderBy(s => s.OrderId).ToList();
                        }

                        //var currentjobs = (from j in lineBuffer.Where(i => i.OrderId >= station.NextBox.OrderId).Take(itemsinschedule).ToList()
                        //                   select new Seat {
                                              
                        //                       OrderStatus = (int)j.OrderStatus,
                        //                       Complete = false,
                        //                       TrimStyle = GetOptionValue(j.ItemNumber.Trim(), 100),
                        //                       Colour = GetOptionValue(j.ItemNumber.Trim(), 101),
                        //                       OrderNumber = j.OrderNumber == null ? "" : j.OrderNumber.Trim(),
                        //                       ItemNumber = j.ItemNumber.Trim(),
                        //                       ItemType = j.ItemType.Trim(),
                        //                       DescLine1 = j.ItemNumber.Trim(),
                        //                       DescLine2 = factory.GetSequencingMessage(station, j.ItemNumber.Trim(), tokens),
                        //                       JobId = (int)j.JobId,
                        //                       OrderId = j.OrderId,
                        //                       Item = itemDetailsModel.GetItemInfoByLineId(j.ItemNumber.Trim(), station.Line.Id),
                        //                   }).OrderBy(s=>s.OrderId).ToList();

                        if (currentjobs.Count() != itemsinschedule)
                            return null;

                        //var lastcurrentjob = currentjobs.Last();

                        //var nextjobs = (from j in lineBuffer.Where(i => i.OrderId > lastcurrentjob.OrderId).Take(itemsinschedule).ToList()
                        //                select new Seat
                        //                {
                        //                    OrderStatus = (int)j.OrderStatus,
                        //                    Complete = false,
                        //                    TrimStyle = GetOptionValue(j.ItemNumber.Trim(), 100),
                        //                    Colour = GetOptionValue(j.ItemNumber.Trim(), 101),
                        //                    OrderNumber = j.OrderNumber == null ? "" : j.OrderNumber.Trim(),
                        //                    ItemNumber = j.ItemNumber.Trim(),
                        //                    ItemType = j.ItemType.Trim(),
                        //                    DescLine1 = j.ItemNumber.Trim(),
                        //                    DescLine2 = factory.GetSequencingMessage(station, j.ItemNumber.Trim(), tokens),
                        //                    JobId = (int)j.JobId,
                        //                    OrderId = j.OrderId,
                        //                    Item = itemDetailsModel.GetItemInfoByLineId(j.ItemNumber.Trim(), station.Line.Id)
                        //                }).OrderBy(s => s.OrderId).ToList();

                        //if (nextjobs.Count() == itemsinschedule)
                        //{
                        //    trimSchedule.NextSchedule = new TrimScheduleInfo
                        //    {
                        //        Complete = false,
                        //        SeatSchedule = nextjobs,
                        //        SummaryList = GetSummaryHeaderItems(nextjobs, station.Line.Id),
                        //        ScheduleStatus = new TrimScheduleStatus
                        //        {
                        //            CurrentBoxNumber = (scheduleStatus.NextBoxNum + 1) > boxqty ? 1 : scheduleStatus.NextBoxNum + 1,
                        //            CurrentScheduleNumber = scheduleStatus.NextScheduleNum + 1
                        //        }
                        //    };
                        //}
                        //else
                        //{
                        //    trimSchedule.NextSchedule = null;
                        //}

                        //for (int i = 0; i < nextjobs.Count(); i++)
                        //    nextjobs[i].Index = i;

                        for(int i=0; i<currentjobs.Count(); i++)
                            currentjobs[i].Index = i;

                        trimSchedule.CurrentSchedule = new TrimScheduleInfo
                        {
                            Complete = false,
                            SeatSchedule = currentjobs,
                            SummaryList = GetSummaryHeaderItems(currentjobs, station.Line.Id),
                            ScheduleStatus = GetTrimScheduleStatus(station, scheduleStatus, currentjobs),
                            OffsetSeats = offsetSeats
                        };

                        return trimSchedule;

                    }
                }
            }
            return null;
        }
 public HttpResponseMessage CompletePlasticSequencingStation(int aisleId, int employeeId)
 {
     SequencingScheduleFactory maker = new SequencingScheduleFactory();
     maker.CompleteSequencingByAisleId(aisleId, employeeId);
     return new HttpResponseMessage(HttpStatusCode.OK);
 }
 public PlasticSeqSchedule ScheduleBySequencingStationId(int id)
 {
     SequencingScheduleFactory maker = new SequencingScheduleFactory();
     PlasticSeqSchedule schedule = maker.GetPlasticSeqScheduleBySequencingStationId(id);
     return schedule;
 }
 public IEnumerable<PlasticSeqSchedule> GetPlasticSeqSchedulesByLocationId(int locationId)
 {
     SequencingScheduleFactory factory = new SequencingScheduleFactory();
     var schedules = factory.GetPlasticSeqSchedulesByLocationId(locationId);
     return schedules;
 }
 public HttpResponseMessage AutoCorrectOffsetByStationId(int id)
 {
     SequencingScheduleFactory maker = new SequencingScheduleFactory();
     maker.AutoCorrectSeqScheduleBySequencingStationId(id);
     return new HttpResponseMessage(HttpStatusCode.OK);
 }
 public HttpResponseMessage UpdateOffsetStationById(int id, int direction, int offset)
 {
     SequencingScheduleFactory maker = new SequencingScheduleFactory();
     maker.UpdateOffsetStationById(id, direction, offset);
     return new HttpResponseMessage(HttpStatusCode.OK);
 }
        public PlasticSeqSchedule GetPlasticScheduleHistoryDetail(SequencingStation station, int scheduleNum)
        {
            PartSequencingDataContext dbSeq = new PartSequencingDataContext();
            SequencingScheduleFactory factory = new SequencingScheduleFactory();
            PlasticSeqSchedule plasticHistorySchedule = new PlasticSeqSchedule();

            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 = factory.GetSequencingMessage(station, s.ItemNumber.Trim(), tokens),
                                            Position = (int)s.Position
                                        }).ToList(),
                           }).ToList();

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

            return plasticHistorySchedule;
        }
        public TrimScheduleInfo GetNextTrimSchedule(int locationId)
        {
            PartSequencingDataContext dbSeq = new PartSequencingDataContext();
            SequencingScheduleFactory factory = new SequencingScheduleFactory();
            MesDataContext dbMes = new MesDataContext();
            ItemDetailsModel itemDetailsModel = new ItemDetailsModel();
            TrimScheduleInfo nextTrimScheduleInfo = null;

            var seqStations = dbSeq.SequencingStationSettings.Where(i => i.SequencingLocationId == locationId).ToList();
            if (seqStations.Count() > 0)
            {
                var seqStation = seqStations.FirstOrDefault();
                if (seqStation != null)
                {
                    var station = factory.UpdateNextBoxBySequencingId(seqStation.Id);
                    var scheduleStatus = dbSeq.SequencingStationLookups.Where(s => s.SequenceStationSettingsId == station.Id).FirstOrDefault();
                    var tokens = MessageTokensCacheManager.MessageTokens.Where(s => s.LineId == station.Line.Id || s.LineId == 4).ToList();

                    var lineBuffer = factory.GetSequencingBuffer(station);

                    if (lineBuffer != null)
                    {
                        var itemsinbox = station.PartsPerBox;
                        var boxperschedule = station.BoxPerSchedule;
                        var itemsinschedule = itemsinbox * boxperschedule;
                        var boxqty = station.BoxQty;

                        var currentjobs = (from j in lineBuffer.Where(i => i.OrderId >= station.NextBox.OrderId).Take(itemsinschedule).ToList()
                                           select new Seat
                                           {
                                               OrderStatus = (int)j.OrderStatus,
                                               Complete = false,
                                               TrimStyle = GetOptionValue(j.ItemNumber.Trim(), 100),
                                               Colour = GetOptionValue(j.ItemNumber.Trim(), 101),
                                               OrderNumber = j.OrderNumber == null ? "" : j.OrderNumber.Trim(),
                                               ItemNumber = j.ItemNumber.Trim(),
                                               ItemType = j.ItemType.Trim(),
                                               DescLine1 = j.ItemNumber.Trim(),
                                               DescLine2 = factory.GetSequencingMessage(station, j.ItemNumber.Trim(), tokens),
                                               JobId = (int)j.JobId,
                                               OrderId = j.OrderId,
                                               Item = itemDetailsModel.GetItemInfoByLineId(j.ItemNumber.Trim(), station.Line.Id),
                                           }).OrderBy(s => s.OrderId).ToList();

                        if (currentjobs.Count() != itemsinschedule)
                            return null;

                        var lastcurrentjob = currentjobs.Last();

                        var nextjobs = (from j in lineBuffer.Where(i => i.OrderId > lastcurrentjob.OrderId).Take(itemsinschedule).ToList()
                                        select new Seat
                                        {
                                            OrderStatus = (int)j.OrderStatus,
                                            Complete = false,
                                            TrimStyle = GetOptionValue(j.ItemNumber.Trim(), 100),
                                            Colour = GetOptionValue(j.ItemNumber.Trim(), 101),
                                            OrderNumber = j.OrderNumber == null ? "" : j.OrderNumber.Trim(),
                                            ItemNumber = j.ItemNumber.Trim(),
                                            ItemType = j.ItemType.Trim(),
                                            DescLine1 = j.ItemNumber.Trim(),
                                            DescLine2 = factory.GetSequencingMessage(station, j.ItemNumber.Trim(), tokens),
                                            JobId = (int)j.JobId,
                                            OrderId = j.OrderId,
                                            Item = itemDetailsModel.GetItemInfoByLineId(j.ItemNumber.Trim(), station.Line.Id)
                                        }).OrderBy(s => s.OrderId).ToList();

                        if (nextjobs.Count() == itemsinschedule)
                        {
                            nextTrimScheduleInfo = new TrimScheduleInfo
                            {
                                Complete = false,
                                SeatSchedule = nextjobs,
                                SummaryList = GetSummaryHeaderItems(nextjobs, station.Line.Id),
                                ScheduleStatus = new TrimScheduleStatus
                                {
                                    CurrentBoxNumber = (scheduleStatus.NextBoxNum + 1) > boxqty ? 1 : scheduleStatus.NextBoxNum + 1,
                                    CurrentScheduleNumber = scheduleStatus.NextScheduleNum + 1
                                }
                            };
                        }
                        else
                        {
                            return null;
                        }

                        for (int i = 0; i < nextjobs.Count(); i++)
                            nextjobs[i].Index = i;

                        return nextTrimScheduleInfo;

                    }
                }
            }
            return null;
        }
        public JobBuffer ScheduleAdminView(int id)
        {
            SequencingScheduleFactory maker = new SequencingScheduleFactory();
            return maker.ScheduleAdminView(id);

        }
        public TrimScheduleInfo GetTrimScheduleHistoryDetail(int locationId, int scheduleNum)
        {
            PartSequencingDataContext dbSeq = new PartSequencingDataContext();
            ItemDetailsModel itemDetailsModel = new ItemDetailsModel();
            SequencingScheduleFactory factory = new SequencingScheduleFactory();

            var seqStation = dbSeq.SequencingStationSettings.Where(i => i.SequencingLocationId == locationId).FirstOrDefault();
            var tokens = MessageTokensCacheManager.MessageTokens.Where(s => s.LineId == seqStation.LineId || s.LineId == 4).ToList();
            var station = factory.UpdateNextBoxBySequencingId(seqStation.Id);

            TrimScheduleInfo trimHistorySchedule = null;

            if (station != null)
            {
                SequencingTrackingItem lastItem = null;
                var tracking = factory.GetSequencingHistory(station);

                if (tracking.Any())
                {
                    lastItem = tracking.OrderByDescending(i => i.OrderId).First();
                    if (lastItem != null)
                    {
                        var historyjobs = (from t in dbSeq.IWS_GetSequencingDetailHistoryBySeqSettingsIdAndScheduleNum(station.Id, scheduleNum)
                                          select new Seat
                                          {
                                            ScheduleNum = t.ScheduleNum,
                                            BoxNum = t.BoxNum,
                                            Complete = false,
                                            TrimStyle = GetOptionValue(t.ItemNumber.Trim(), 100),
                                            Colour = GetOptionValue(t.ItemNumber.Trim(), 101),
                                            ItemNumber = t.ItemNumber.Trim(),
                                            ItemType = t.ItemType.Trim(),
                                            DescLine1 = t.ItemNumber.Trim(),
                                            DescLine2 = factory.GetSequencingMessage(station, t.ItemNumber.Trim(), tokens),
                                            OrderId = t.OrderId,
                                            Item = itemDetailsModel.GetItemInfoByLineId(t.ItemNumber.Trim(), station.Line.Id)
                                          }).ToList();

                                          

                        //var historyjobs = (from t in tracking
                        //                    select new Seat
                        //                    {
                        //                        Complete = false,
                        //                        TrimStyle = GetOptionValue(t.ItemNumber.Trim(), 100),
                        //                        Colour = GetOptionValue(t.ItemNumber.Trim(), 101),
                        //                        ItemNumber = t.ItemNumber.Trim(),
                        //                        ItemType = t.ItemType.Trim(),
                        //                        DescLine1 = t.ItemNumber.Trim(),
                        //                        DescLine2 = factory.GetSequencingMessage(station, t.ItemNumber.Trim(), tokens),
                        //                        JobId = (int)t.JobId,
                        //                        OrderId = t.OrderId,
                        //                        Item = itemDetailsModel.GetItemInfoByLineId(t.ItemNumber.Trim(), station.Line.Id)
                        //                    }).ToList();

                        var firstItem = historyjobs.FirstOrDefault();

                        trimHistorySchedule = new TrimScheduleInfo
                        {
                            Complete = true,
                            ScheduleStatus = new TrimScheduleStatus
                            {
                                CurrentBoxNumber = firstItem == null ? 0 : firstItem.BoxNum,
                                CurrentScheduleNumber = firstItem == null ? 0 : firstItem.ScheduleNum
                            },
                            SeatSchedule = historyjobs,
                            SummaryList = GetSummaryHeaderItems(historyjobs, station.Line.Id),
                        };
                        return trimHistorySchedule;
                    }

                }

            }
            return trimHistorySchedule;

            
        }
        public IEnumerable<PlasticSeqSchedule> GetPlasticScheduleHistoryDetailByLocationId(int locationId, int scheduleNum)
        {
            SequencingScheduleFactory factory = new SequencingScheduleFactory();
            PlasticSeqDatabase db = new PlasticSeqDatabase();

            List<PlasticSeqSchedule> listPlasticHistory = new List<PlasticSeqSchedule>();

            var seqStations = db.GetSequencingStationsBySequencingLocationId(locationId);

            foreach (var station in seqStations)
            {
                var schedule = factory.GetPlasticScheduleHistoryDetail(station, scheduleNum);
                listPlasticHistory.Add(schedule);
            }

            return listPlasticHistory;
        }
        public IEnumerable<SequencingStation> GetSequencingStationsBySequencingLocationId(int id)
        {
            PartSequencingDataContext dbSeq = new PartSequencingDataContext();
            MesDataContext dbMes = new MesDataContext();
            SequencingScheduleFactory factory = new SequencingScheduleFactory();
            List<SequencingStation> listStations = new List<SequencingStation>();

            var results = (from s in SequencingSettingsCacheManager.SequencingStationSettings
                               where s.SequencingLocationId == id
                               select s).ToList();

            foreach (var seqStation in results)
            {
                var station = factory.UpdateNextBoxBySequencingId(seqStation.Id);
                listStations.Add(station);
            }

            return listStations;
        }
 public IEnumerable<SequencingStationScheduleHistory> SequencingScheduleHistory(int id)
 {
     SequencingScheduleFactory factory = new SequencingScheduleFactory();
     var items = factory.GetScheduleHistory(id);
     return items;
 }