﻿using AutoMapper;
using ManagerShop.Data.DbContent;
using ManagerShop.Domain.DomainServices.System;
using ManagerShop.Domain.IRepository.System;
using ManagerShop.Domain.System;
using ManagerShop.DTOModel;
using ManagerShop.DTOModel.System;
using ManagerShop.Infrastructure.Core;
using ManagerShop.Infrastructure.Core.Ioc;
using ManagerShop.Service.Contract.System;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace ManagerShop.Application.Service.System
{
    public class MenuAppService : IMenuAppService
    {
        public IMenuRepository imenurepository { get; set; }

        public IRoleRepository irolerepository { get; set; }

        public List<DTO_MENU> GetMenuList()
        {
            try
            {
                return (AutoMapper.Mapper.Map<List<DTO_MENU>>(imenurepository.IQueryable().ToList()));
            }
            catch (Exception ex)
            {
                Logger.Out(this.GetType(), LoggerEnum.Error, ex);
                return null;
            }
        }


        public ServiceResult UpdateRoleMenus(String RoleId, String[] Menus)
        {
            try
            {
                using (var unitofwork = new EFUnitOfWork())
                {
                    IMenuRepository _imenurepository = unitofwork.repository<IMenuRepository>();
                    IRoleRepository _irolerepository = unitofwork.repository<IRoleRepository>();

                    var RoleModel = _irolerepository.GetById(RoleId);
                    _irolerepository.UpdateTo(RoleModel);
                    RoleModel.Menulist.Clear();
                    if (Menus != null)
                    {
                        var listMenus = Menus.ToList();
                        var listmenu = new List<MenuEntity>();
                        listmenu = _imenurepository.IQueryable().Where(x => listMenus.Contains(x.M_Id)).ToList();
                        RoleModel.Menulist = listmenu;
                    }
                    

                    if (!unitofwork.IsCommitted)
                        unitofwork.Commit();
                }

                return new ServiceResult();
            }
            catch (Exception ex)
            {
                Logger.Out(this.GetType(), LoggerEnum.Error, ex);
                return new ServiceResult(ex.Message);
            }
        }
    }
}