namespace ServiceCenter.Data.BLT
{
    #region Using
    using System;
    using System.Collections.Generic;
    using System.Linq;

    using BLToolkit.Data;
    using BLToolkit.Data.Linq;
    using BLToolkit.Linq;
    #endregion

    public class DataService
    {
        #region Конструктор
        public DataService()
        {
            BLToolkit.Common.Configuration.Linq.AllowMultipleQuery = true;
        }
        #endregion

        #region Производитель
        /// <summary>
        /// Возвращает список всех производителей
        /// </summary>
        public List<Manufacturer> GetManufacturers()
        {
            List<Manufacturer> result = null;

            using (ServiceCenterDB db = new ServiceCenterDB())
            {
                result = db.Manufacturers.ToList();
            }

            return result;
        }

        /// <summary>
        /// Возвращает производителя
        /// </summary>
        public Manufacturer GetManufacturer(int id)
        {
            Manufacturer result = null;

            using (ServiceCenterDB db = new ServiceCenterDB())
            {
                result = (from x in db.Manufacturers
                          where x.Id == id
                          select new Manufacturer(x)
                          {
                              Requests = (from y in db.Requests
                                          where y.Manufacturer == x
                                          select new Request(y)
                                          {
                                              Employee = y.Employee,
                                              DeviceType = y.DeviceType,
                                              Manufacturer = x,
                                              Status = y.Status
                                          }).ToList()
                          }).FirstOrDefault();
            }

            return result;
        }

        /// <summary>
        /// Сохранить производителя
        /// </summary>
        public void SaveManufacturer(Manufacturer manufacturer)
        {
            using (ServiceCenterDB db = new ServiceCenterDB())
            {
                if (manufacturer.Id == 0)
                    db.Into(db.Manufacturers).Value(x => x.Value, manufacturer.Value).Insert();
                else
                    db.Manufacturers.Where(x => x.Id == manufacturer.Id).Set(x => x.Value, manufacturer.Value).Update();
            }
        }

        /// <summary>
        /// Удалить производителя
        /// </summary>
        public void DeleteManufacturer(Manufacturer manufacturer)
        {
            using (ServiceCenterDB db = new ServiceCenterDB())
            {
                db.Manufacturers.Where(x => x.Id == manufacturer.Id).Delete();
            }
        }
        #endregion

        #region Состояние заявки
        /// <summary>
        /// Возвращает список всех состояний заявок
        /// </summary>
        public List<Status> GetStatuses()
        {
            List<Status> result = null;

            using (ServiceCenterDB db = new ServiceCenterDB())
            {
                result = db.Statuses.ToList();
            }

            return result;
        }

        /// <summary>
        /// Возвращает состояние заявки
        /// </summary>
        public Status GetStatus(int id)
        {
            Status result = null;

            using (ServiceCenterDB db = new ServiceCenterDB())
            {
                result = (from x in db.Statuses
                          where x.Id == id
                          select new Status(x)
                          {
                              Requests = (from y in db.Requests
                                          where y.Status == x
                                          select new Request(y)
                                          {
                                              Employee = y.Employee,
                                              DeviceType = y.DeviceType,
                                              Manufacturer = y.Manufacturer,
                                              Status = x
                                          }).ToList()
                          }).FirstOrDefault();
            }

            return result;
        }

        /// <summary>
        /// Сохранить состояние заявки
        /// </summary>
        public void SaveStatus(Status status)
        {
            using (ServiceCenterDB db = new ServiceCenterDB())
            {
                if (status.Id == 0)
                    db.Into(db.Statuses).Value(x => x.Value, status.Value).Insert();
                else
                    db.Statuses.Where(x => x.Id == status.Id).Set(x => x.Value, status.Value).Update();
            }
        }

        /// <summary>
        /// Удалить состояние заявки
        /// </summary>
        public void DeleteStatus(Status status)
        {
            using (ServiceCenterDB db = new ServiceCenterDB())
            {
                db.Statuses.Where(x => x.Id == status.Id).Delete();
            }
        }
        #endregion

        #region Тип устройства
        /// <summary>
        /// Возвращает список всех типов устройств
        /// </summary>
        public List<DeviceType> GetDeviceTypes()
        {
            List<DeviceType> result = null;

            using (ServiceCenterDB db = new ServiceCenterDB())
            {
                result = db.DeviceTypes.ToList();
            }

            return result;
        }

        /// <summary>
        /// Возвращает тип устройства
        /// </summary>
        public DeviceType GetDeviceType(int id)
        {
            DeviceType result = null;

            using (ServiceCenterDB db = new ServiceCenterDB())
            {
                result = (from x in db.DeviceTypes
                          where x.Id == id
                          select new DeviceType(x)
                          {
                              Requests = (from y in db.Requests
                                          where y.DeviceType == x
                                          select new Request(y)
                                          {
                                              Employee = y.Employee,
                                              DeviceType = x,
                                              Manufacturer = y.Manufacturer,
                                              Status = y.Status
                                          }).ToList()
                          }).FirstOrDefault();
            }

            return result;
        }

        /// <summary>
        /// Сохранить тип устройства
        /// </summary>
        public void SaveDeviceType(DeviceType deviceType)
        {
            using (ServiceCenterDB db = new ServiceCenterDB())
            {
                if (deviceType.Id == 0)
                    db.Into(db.DeviceTypes).Value(x => x.Value, deviceType.Value).Insert();
                else
                    db.DeviceTypes.Where(x => x.Id == deviceType.Id).Set(x => x.Value, deviceType.Value).Update();
            }
        }

        /// <summary>
        /// Удалить тип устройства
        /// </summary>
        public void DeleteDeviceType(DeviceType deviceType)
        {
            using (ServiceCenterDB db = new ServiceCenterDB())
            {
                db.DeviceTypes.Where(x => x.Id == deviceType.Id).Delete();
            }
        }
        #endregion

        #region Должности
        /// <summary>
        /// Возвращает список всех должностей
        /// </summary>
        public List<Position> GetPositions()
        {
            List<Position> result = null;

            using (ServiceCenterDB db = new ServiceCenterDB())
            {
                result = db.Positions.ToList();
            }

            return result;
        }

        /// <summary>
        /// Возвращает должность
        /// </summary>
        public Position GetPosition(int id)
        {
            Position result = null;

            using (ServiceCenterDB db = new ServiceCenterDB())
            {
                result = (from x in db.Positions
                          where x.Id == id
                          select new Position(x)
                          {
                              Employees = (from y in db.Employees
                                           where y.Position == x
                                           select new Employee(y)
                                           {
                                               Position = x
                                           }).ToList()
                          }).FirstOrDefault();
            }

            return result;
        }

        /// <summary>
        /// Сохранить должность
        /// </summary>
        public void SavePosition(Position position)
        {
            using (ServiceCenterDB db = new ServiceCenterDB())
            {
                if (position.Id == 0)
                    db.Into(db.Positions).Value(x => x.Value, position.Value).Insert();
                else
                    db.Positions.Where(x => x.Id == position.Id).Set(x => x.Value, position.Value).Update();
            }
        }

        /// <summary>
        /// Удалить должность
        /// </summary>
        public void DeletePosition(Position position)
        {
            using (ServiceCenterDB db = new ServiceCenterDB())
            {
                db.Positions.Where(x => x.Id == position.Id).Delete();
            }
        }
        #endregion

        #region Сотрудники
        /// <summary>
        /// Возвращает список всех сотрудников
        /// </summary>
        public List<Employee> GetEmployees()
        {
            List<Employee> result = null;

            using (ServiceCenterDB db = new ServiceCenterDB())
            {
                var query = from x in db.Employees
                            orderby x.SurName, x.Name
                            select new Employee(x)
                            {
                                Position = x.Position
                            };

                result = query.ToList();
            }

            return result;
        }

        /// <summary>
        /// Возвращает сотрудника
        /// </summary>
        public Employee GetEmployee(int id)
        {
            Employee result = null;

            using (ServiceCenterDB db = new ServiceCenterDB())
            {
                result = (from x in db.Employees
                          where x.Id == id
                          select new Employee(x)
                          {
                              Position = x.Position,
                              Requests = (from y in db.Requests
                                          where y.Employee == x
                                          select new Request(y)
                                          {
                                              Employee = x,
                                              DeviceType = y.DeviceType,
                                              Manufacturer = y.Manufacturer,
                                              Status = y.Status
                                          }).ToList()
                          }).FirstOrDefault();
            }

            return result;
        }

        /// <summary>
        /// Сохранить сотрудника
        /// </summary>
        public void SaveEmployee(Employee employee)
        {
            using (ServiceCenterDB db = new ServiceCenterDB())
            {
                if (employee.Id == 0)
                    db.Into(db.Employees)
                        .Value(x => x.SurName, employee.SurName)
                        .Value(x => x.Name, employee.Name)
                        .Value(x => x.MidName, employee.MidName)
                        .Value(x => x.PositionId, employee.PositionId).Insert();
                else
                    db.Employees.Where(x => x.Id == employee.Id)
                        .Set(x => x.SurName, employee.SurName)
                        .Set(x => x.Name, employee.Name)
                        .Set(x => x.MidName, employee.MidName)
                        .Set(x => x.PositionId, employee.PositionId).Update();
            }
        }

        /// <summary>
        /// Удалить сотрудника
        /// </summary>
        public void DeleteEmployee(Employee employee)
        {
            using (ServiceCenterDB db = new ServiceCenterDB())
            {
                db.Employees.Where(x => x.Id == employee.Id).Delete();
            }
        }
        #endregion

        #region Заявки
        /// <summary>
        /// Возвращает список всех заявок
        /// </summary>
        public List<Request> GetRequests()
        {
            List<Request> result = null;

            using (ServiceCenterDB db = new ServiceCenterDB())
            {
                var query = from x in db.Requests
                            orderby x.DateIn
                            select new Request(x)
                            {
                                Employee = x.Employee,
                                DeviceType = x.DeviceType,
                                Manufacturer = x.Manufacturer,
                                Status = x.Status
                            };

                result = query.ToList();
            }

            return result;
        }

        /// <summary>
        /// Возвращает заявку
        /// </summary>
        public Request GetRequest(int id)
        {
            Request result = null;

            using (ServiceCenterDB db = new ServiceCenterDB())
            {
                result = (from x in db.Requests
                          where x.Id == id
                          select new Request(x)
                          {
                              Employee = x.Employee,
                              DeviceType = x.DeviceType,
                              Manufacturer = x.Manufacturer,
                              Status = x.Status
                          }).FirstOrDefault();
            }

            return result;
        }

        /// <summary>
        /// Сохранить заявку
        /// </summary>
        public void SaveRequest(Request request)
        {
            using (ServiceCenterDB db = new ServiceCenterDB())
            {
                if (request.Id == 0)
                    db.Into(db.Requests)
                        .Value(x => x.EmployeeId, request.EmployeeId)
                        .Value(x => x.DateIn, Sql.CurrentTimestamp2)
                        .Value(x => x.DeviceTypeId, request.DeviceTypeId)
                        .Value(x => x.ManufacturerId, request.ManufacturerId)
                        .Value(x => x.Model, request.Model)
                        .Value(x => x.Description, request.Description)
                        .Value(x => x.ClientName, request.ClientName)
                        .Value(x => x.ClientPhone, request.ClientPhone)
                        .Value(x => x.Cost, request.Cost)
                        .Value(x => x.StatusId, request.StatusId).Insert();
                else
                    db.Requests.Where(x => x.Id == request.Id)
                        .Set(x => x.EmployeeId, request.EmployeeId)
                        .Set(x => x.DateOut, request.StatusId == 5 || request.StatusId == 6 ? Sql.CurrentTimestamp2 : (DateTime?)null)
                        .Set(x => x.DeviceTypeId, request.DeviceTypeId)
                        .Set(x => x.ManufacturerId, request.ManufacturerId)
                        .Set(x => x.Model, request.Model)
                        .Set(x => x.Description, request.Description)
                        .Set(x => x.ClientName, request.ClientName)
                        .Set(x => x.ClientPhone, request.ClientPhone)
                        .Set(x => x.Cost, request.Cost)
                        .Set(x => x.StatusId, request.StatusId)
                        .Set(x => x.Comment, request.Comment).Update();
            }
        }

        /// <summary>
        /// Удалить заявку
        /// </summary>
        public void DeleteRequest(Request request)
        {
            using (ServiceCenterDB db = new ServiceCenterDB())
            {
                db.Requests.Where(x => x.Id == request.Id).Delete();
            }
        }
        #endregion
    }
}
