﻿using System.Collections.Generic;
using System.Linq;
using SOURCE.Domaine;
using SOURCE.Domaine.Composite;
using System.Data.SqlClient;
using System.Data;
using SOURCE.Domaine.Results;
using SOURCE.Business.Depots;
using SOURCE.Data.Context;

namespace SOURCE.Data.Depots
{
    public partial class DepotEdition : IDepotEdition
    {
        private readonly IDepotTraduction _traduction;

        public DepotEdition(ISourceDbContext dataContext,
            IDepotTraduction traduction)
            : this(dataContext)
        {
            _traduction = traduction;
        }



        public IQueryable<Edition> GetByRights(IEnumerable<DroitDto> droits)
        {
            long[] droitsID = droits.Select(x => x.ID).ToArray();

            var query = from l in DbContext.Lien_Droit_Editions
                        join e in DbContext.Editions on l.EditionID equals e.ID
                        where droitsID.Contains(l.DroitID)
                        select e;

            return query;
        }

        public IQueryable<Edition> GetAllEdition()
        {
            var edition = from d in DbContext.Editions.OrderBy(x => x.LibelleEntite)
                          select d;
            return edition;
        }

        public Edition GetEditionById(long idEdition)
        {
            return DbContext.Editions.FirstOrDefault(d => d.ID.Equals(idEdition));
        }

   

        public IQueryable<TypeRestitutionEdition> GetTypeRestitution()
        {
            var query = from a in DbContext.TypeRestitutionEditions

                        select a;
            return query;

        }

        public IEnumerable<EditionResult> Search(string description)
        {
            List<SqlParameter> Parameters = new List<SqlParameter>();

            Parameters.Add(new SqlParameter("@Description", SqlDbType.NVarChar) { Value = description });

            return DbContext.ExecuteStoredProcedure<EditionResult>("sp_SearchEditions", Parameters);
        }

        public EditionDto SaveEditionInfosGenerales(EditionDto edition)
        {
            Edition _edition;

            if (edition.ID > 0)
                _edition = GetById(edition.ID);
            else
                _edition = new Edition();

            _edition.TypeEdition = edition.TypeEdition > 0 ? edition.TypeEdition : 0;
            _edition.Description = edition.Description;

            _edition.VueID = edition.VueID;
 
            _edition.CheminRdl = edition.CheminRdl;

            _edition.TypeRestitutionEditionID = edition.TypeRestitutionEditionID;
            
            if (edition.ID > 0)
                Update();
            else
            {
                Add(_edition);
                // lors de la création du profil on créer par default ses traduction
                _traduction.TraduireTable("Edition");
            }


            var dto = GetEditionById(_edition.ID);

            return AutoMapper.Mapper.Map<Edition, EditionDto>(dto);
        }
    }
}