using System.Collections.Generic;
using System.Threading.Tasks;
using AutoMapper;
using Datory;
using GxPress.Common.AppOptions;
using GxPress.Common.Tools;
using GxPress.Repository.Interface.Menus;
using Microsoft.Extensions.Options;
using System.Linq;
namespace GxPress.Repository.Implement.Menus
{
    public class MenusRepository : IMenusRepository
    {
        private readonly Repository<Entity.Menus.Menus> _repository;
        private readonly IMapper _mapper;

        public MenusRepository(IOptionsMonitor<DatabaseOptions> dbOptionsAccessor, IMapper mapper)
        {
            var databaseType = StringUtils.ToEnum<DatabaseType>(dbOptionsAccessor.CurrentValue.DatabaseType, DatabaseType.MySql);
            var database = new Database(databaseType, dbOptionsAccessor.CurrentValue.ConnectionString);
            _repository = new Repository<Entity.Menus.Menus>(database);
            _mapper = mapper;
        }

        public IDatabase Database => _repository.Database;
        public string TableName => _repository.TableName;
        public List<TableColumn> TableColumns => _repository.TableColumns;

        public async Task<int> InsertAsync(Entity.Menus.Menus model)
        {
            return await _repository.InsertAsync(model);

        }

        public async Task<bool> UpdateAsync(Entity.Menus.Menus model)
        {
            return await _repository.UpdateAsync(model);
        }

        public async Task<bool> DeleteAsync(int id)
        {
            return await _repository.DeleteAsync(id);
        }

        public async Task<IEnumerable<Entity.Menus.Menus>> GetAllAsync()
        {
            var all = await _repository.GetAllAsync();
            var list = new List<Entity.Menus.Menus>();
            list = all.Where(n => n.ParentId == 0).ToList();
            foreach (var item in list)
            {
                item.Children = all.Where(n => n.ParentId == item.Id).ToList();
            }
            return list;
        }

        public async Task<IEnumerable<Entity.Menus.Menus>> GetAllAsync(List<int> menusIds)
        {
            var all = await _repository.GetAllAsync(Q.WhereIn(nameof(Entity.Menus.Menus.Id), menusIds));
            var list = new List<Entity.Menus.Menus>();
            list = all.Where(n => n.ParentId == 0).ToList();
            foreach (var item in list)
            {
                item.Children = all.Where(n => n.ParentId == item.Id).ToList();
            }
            return list;
        }

         public async Task<IEnumerable<Entity.Menus.Menus>> GetAllMenusAsync(List<int> menusIds)
        {
            var all = await _repository.GetAllAsync(Q.WhereIn(nameof(Entity.Menus.Menus.Id), menusIds));
           return all;
        }
    }
}