public Employee GetAuthEmployeeInfo(int id)
        {            
            try
            {
                var employeeDb = new EmployeeDatabase();
                var emp = employeeDb.GetEmployeeInfo(id);

                if (emp == null)
                {
                    throw new HttpResponseException(
                        HttpErrorResponse.GetHttpErrorResponse(
                        HttpStatusCode.NotFound, "Employee ID does not exist", string.Format("Employee with ID = {0} does not exist", id)));
                }
                else
                {
                    List<string> authorizedJobs = new List<string> { "ROLE_UP", "ROLE_SUP", "ROLE_IT", "ROLE_PM", "ROLE_ASM" };
                    if (authorizedJobs.Contains(emp.Role.Trim()))
                        return emp;
                    else
                    {
                        throw new HttpResponseException(
                            HttpErrorResponse.GetHttpErrorResponse(
                            HttpStatusCode.Unauthorized, "Employee ID does not have permission", string.Format("Employee with ID = {0} does not have permission", id)));
                    }
                }

            }
            catch (InvalidOperationException ex)
            {
                throw new HttpResponseException(
                    HttpErrorResponse.GetHttpErrorResponse(
                    HttpStatusCode.NotFound, "Employee ID does not exist", string.Format("Employee with ID = {0} does not exist", id)));
            }


        }
        public void SaveRepairHistory(RepairFaults repairFaults, MasterJobTable jobInfo, PalletInfo palletInfo, string empId)
        {
            REWORK_REPORTINGEntities entities = new REWORK_REPORTINGEntities();
            EmployeeDatabase dbEmp = new EmployeeDatabase();
            var emp = dbEmp.GetEmployeeInfo(int.Parse(empId));

            var history = new RepairHistory
            {
                ArriveDtm = DateTime.Now,
                CompletedDtm = DateTime.Now,
                PalletId = palletInfo.PalletNbr,
                EmployeeId = int.Parse(emp.EmployeeId),
                EmployeeName = emp.Name.Trim(),
                JobId = jobInfo.Job_ID,
                RepairFaultXrefRepairHistories = GetRepairFaultXrefRepairHistories(repairFaults),
                RepairTestRequirements = GetRepairTestRequirements(repairFaults)
            };

            entities.RepairHistories.Add(history);

            try
            {
                entities.SaveChanges();
            }
            catch (DbEntityValidationException dbEx)
            {
                foreach (var validationErrors in dbEx.EntityValidationErrors)
                {
                    foreach (var validationError in validationErrors.ValidationErrors)
                    {
                        Console.WriteLine("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);
                    }
                }
                throw dbEx;
            }
        }
        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 void CompleteSequencingByAisleId(int id, int employeeId)
        {
            PartSequencingDataContext dbSeq = new PartSequencingDataContext();
            EmployeeDatabase dbEmp = new EmployeeDatabase();
            PlasticSeqDatabase db = new PlasticSeqDatabase();
            var seqStations = db.GetSequencingStationsBySequencingLocationId(id);

            int scheduleNum = 0;
            if (seqStations.Count() > 0)
            {
                var first = seqStations.FirstOrDefault();
                if (first != null)
                {
                    scheduleNum = first.NextBox.ScheduleNum;
                }
            }

            foreach (var station in seqStations)
                CompleteSequencingStation(station.Id);

            var employee = dbEmp.GetEmployeeInfo(employeeId);

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

            dbSeq.SequencingStationScheduleHistories.InsertOnSubmit(scheduleHist);
            dbSeq.SubmitChanges();
        }