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 TypeCollegeFactory : Internal.BaseFactory<Entity.TypeCollege>
    {
        public override IQueryable<Entity.TypeCollege> getAll()
        {
            return base.getAll("Ordre");
        }

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

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

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

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

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

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

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

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

            base.add(ref entity);
        }

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