using AutoMapper;
using Performance.DtoModels;
using Performance.EntityModels;
using Performance.Repository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Performance.Services
{
    public class MenuService : IAutoInjection
    {
        private readonly IMapper _mapper;
        private PerforMenuRepository _menuRepository;
        public MenuService(
            IMapper mapper,
            PerforMenuRepository menuRepository)
        {
            _mapper = mapper;
            _menuRepository = menuRepository;
        }

        public List<MenuResponse> GetMenuList(int userid)
        {
            var menuList = _menuRepository.GetMenuList(userid);

            return RecursionFill(menuList, 0);
        }

        private List<MenuResponse> RecursionFill(List<sys_menu> menuList, int parentId)
        {
            if (menuList.Any(t => t.ParentID == parentId))
            {
                var list = new List<MenuResponse>();
                foreach (var item in menuList.Where(t => t.ParentID == parentId).OrderBy(t => t.Sort))
                {
                    var menu = _mapper.Map<MenuResponse>(item);
                    menu.Children = RecursionFill(menuList, item.ID);
                    list.Add(menu);
                }
                return list;
            }
            return null;
        }
    }
}
