﻿using EzApp.Data.Core;
using EzApp.Mapping.Core;
using EzApp.Search.Core;
using EzApp.Services.Core.Options;
using System;
using System.Collections.Generic;
using System.Linq;
using EzApp.Data.Core.Repositories;

namespace EzApp.Services.Options
{
    public class EzOptionsGetter<TOption, TEntity, TEntityId, TEntityFilters>
        :
        IEzOptionsGetter
            <TOption>

        where TOption : class
        where TEntityId : IEquatable<TEntityId>
        where TEntityFilters : IEzEntityFilters<TEntityId>
    {
        public EzOptionsGetter(IEzMapper mapper, IEzEntityReadRepository<TEntity, TEntityId, TEntityFilters> repository)
        {
            Mapper = mapper;
            Repository = repository;
        }

        protected readonly IEzMapper Mapper;
        protected readonly IEzEntityReadRepository<TEntity, TEntityId, TEntityFilters> Repository;
        
        public ICollection<TOption> GetOptions()
        {
            ICollection<TOption> options = null;

            var results = Repository.SelectAll();
                
            if (results != null)
            {
                options = RepositoryResultsToOptions(results);
            }

            return options;
        }

        protected virtual ICollection<TOption> RepositoryResultsToOptions(IEnumerable<TEntity> repositoryResults)
        {
            return repositoryResults.Select(x => Mapper.Map<TEntity, TOption>(x)).ToList();
        }
    }
}
