using LinqToDB;
using MasaBlazorApp3.DataAccess.Dao;
using MasaBlazorApp3.Pojo;
using MasaBlazorApp3.Pojo.Config;
using Microsoft.Extensions.Options;
using System.Linq;

namespace MasaBlazorApp3.DataAccess.Impl
{
    public class RoleDao : IRoleDao
    {

        private AppDataConnection _connection;
        private readonly SettingConfig _setting;

        public RoleDao(AppDataConnection connection, IOptions<SettingConfig> setting) { _connection = connection; _setting = setting.Value; }

        public async Task<Role> GetRoleById(int id)
        {
            return await _connection.Role.AsQueryable().FirstAsync(x => x.Id == id);
        }


        public int InsertRole(Role role)
        {
            role.MachineId = _setting.machineId;
            return _connection.InsertWithInt32Identity(role);
        }

        public bool UpdateRole(Role role)
        {
            int r = _connection.Role
                .Where(r => r.Id == role.Id)
                .Set(r => r.RoleName, role.RoleName)
                .Set(r => r.permissions, role.permissions)
                .Update();
            return r > 0;
        }

        public bool DeleteRole(int id)
        {
            return _connection.Role.Where(r => r.Id ==id).Delete() > 0;
        }

        public async Task<PageData<Role>> GetRolesByName(string name, int? take, int? skip)
        {
            var query = _connection.Role.AsQueryable();
            
            if (!String.IsNullOrEmpty(name))
            {
                query = query.Where(r => r.RoleName.IndexOf(name) > -1);
            }
            query = query.Where(r => r.MachineId == _setting.machineId);

            List<Role> list = await query
                .OrderBy(r => r.Id)
                .Skip((int)skip)
                .Take((int)take)
                .ToListAsync();

            int pagedData = await query.CountAsync();
            return new PageData<Role>()
            {

                TotalDesserts = pagedData,
                Desserts = list
            };
        }

        public async Task<List<Role>> GetAllRoles()
        {
            return await _connection.Role.Where(r => r.MachineId == _setting.machineId).ToListAsync();
        }
    }
}
