using CD67.FicheCollege.Entity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Entity;

namespace CD67.FicheCollege.Factory
{
    public partial class RestaurationTypesRepaFactory : Internal.BaseFactory<Entity.RestaurationTypesRepa>
    {
        public override IQueryable<Entity.RestaurationTypesRepa> getAll()
        {
            return base.getAll("Ordre");
        }

        public IQueryable<Entity.RestaurationTypesRepa> getAllValid()
        {
            return base.getAll("Ordre").Where(i => i.Valid == true);
        }

        public IQueryable<Entity.RestaurationTypesRepa> getAllValid(RestaurationParametre param)
        {
            if (param.RestaurationTypesRepas.Count == 0) this.dbContext.Entry(param).Collection(i => i.RestaurationTypesRepas).Load();
            IQueryable<Entity.RestaurationTypesRepa> typeRepas = param.RestaurationTypesRepas.AsQueryable();

            return typeRepas.Where(i => i.Valid == true).OrderBy(i => i.Ordre);
        }

        public void Up(ref Entity.RestaurationTypesRepa item)
        {
            int ordre = item.Ordre;

            //Cas de sortie immédiate
            if (item.Ordre == 1) return;

            Entity.RestaurationTypesRepa itemToSubstitute = dbContext.RestaurationTypesRepas.Where(i => i.Ordre == ordre - 1).First();
            itemToSubstitute.Ordre += 1;
            item.Ordre -= 1;
            dbContext.SaveChanges();
        }

        public void Down(ref Entity.RestaurationTypesRepa item)
        {
            int ordre = item.Ordre;

            //Cas de sortie immédiate
            if (item.Ordre == dbContext.RestaurationTypes.Max(i => i.Ordre)) return;

            Entity.RestaurationTypesRepa itemToSubstitute = dbContext.RestaurationTypesRepas.Where(i => i.Ordre == ordre + 1).First();
            itemToSubstitute.Ordre -= 1;
            item.Ordre += 1;
            dbContext.SaveChanges();
        }

        private void Sort()
        {
            int ordre = 1;
            foreach (Entity.RestaurationTypesRepa statut in dbContext.RestaurationTypesRepas.OrderBy(i => i.Ordre))
            {
                statut.Ordre = ordre++;
            }
            dbContext.SaveChanges();
        }

        public override void add(ref Entity.RestaurationTypesRepa entity)
        {
            //Initialisation de l'ordre
            if (dbContext.RestaurationTypesRepas.Count() == 0) entity.Ordre = 1;
            else entity.Ordre = dbContext.RestaurationTypesRepas.Max(i => i.Ordre) + 1;

            base.add(ref entity);
        }

        public override void delete(ref Entity.RestaurationTypesRepa entity)
        {
            base.delete(ref entity);
            Sort();
        }
    }
}