public async Task<User> GetUser(UserFilter filter)
        {
            var user = await Task.FromResult(_userDataStore.FdpUserGet(filter));
            user.Roles = _userDataStore.FdpUserGetRoles(user);
            user.Markets = _userDataStore.FdpUserMarketMappingsGetMany(user);
            user.Programmes = _userDataStore.FdpUserProgrammeMappingsGetMany(user);

            return user;
        }
 public static async Task<UserViewModel> GetModel(IDataContext context,
                                                    UserFilter filter)
 {
     if (!string.IsNullOrEmpty(filter.CDSId))
     {
         return await GetFullAndPartialViewModelForUser(context, filter);
     }
     return await GetFullAndPartialViewModelForUsers(context, filter);
 }
        public static async Task<UserViewModel> GetModel(IDataContext context,
                                                           UserFilter filter,
                                                           UserAdminAction action)
        {
            var model = await GetModel(context, filter);
            model.CurrentAction = action;
            if (action != UserAdminAction.NoAction)
            {
                model.IdentifierPrefix = Enum.GetName(action.GetType(), action);
            }

            return model;
        }
 public User FdpUserGet(UserFilter filter)
 {
     User user;
     var results = FdpUserGetMany(filter);
     if (results.CurrentPage.Any())
     {
         user = results.CurrentPage.First().ToUser();
     }
     else
     {
         user = new User
         {
             CDSId = filter.CDSId
         };
     }
     return user;
 }
        private static async Task<UserViewModel> GetFullAndPartialViewModelForUsers(IDataContext context,
                                                                                    UserFilter filter)
        {
            var baseModel = GetBaseModel(context);
            var model = new UserViewModel(baseModel)
            {
                PageIndex = filter.PageIndex ?? 1,
                PageSize = filter.PageSize ?? int.MaxValue,
                Configuration = context.ConfigurationSettings,
                Users = await context.User.ListUsers(filter)
            };
            model.TotalPages = model.Users.TotalPages;
            model.TotalRecords = model.Users.TotalRecords;
            model.TotalDisplayRecords = model.Users.TotalDisplayRecords;

            return model;
        }
        private static async Task<UserViewModel> GetFullAndPartialViewModelForUser(IDataContext context,
                                                                                   UserFilter filter)
        {
            var modelBase = GetBaseModel(context);
            var model = new UserViewModel(modelBase)
            {
                PageIndex = filter.PageIndex ?? 1,
                PageSize = filter.PageSize ?? int.MaxValue,
                Configuration = context.ConfigurationSettings,
                User = await context.User.GetUser(filter),
                Programmes = context.Vehicle.ListProgrammes(new ProgrammeFilter()),
                Markets = await context.Market.ListAvailableMarkets()
            };
            model.CarLines = model.Programmes.ListCarLines();

            return model;
        }
        public IEnumerable<UserRole> FdpUserRolesSave(UserFilter filter)
        {
            var retVal = Enumerable.Empty<UserRole>();

            using (var conn = DbHelper.GetDBConnection())
            {
                try
                {
                    var para = new DynamicParameters();
                    para.Add("@CDSId", filter.CDSId, DbType.String);
                    para.Add("@RoleIds", filter.Permissions, DbType.String);
                    para.Add("@CreatorCDSId", CurrentCDSID, DbType.String);

                    var results = conn.Query<FdpUserRoleDataItem>("dbo.Fdp_UserRoles_Save", para, commandType: CommandType.StoredProcedure);
                    var enumerable = results as IList<FdpUserRoleDataItem> ?? results.ToList();
                    if (enumerable.Any())
                    {
                        retVal = enumerable.Select(r => (UserRole) r.FdpUserRoleId);
                    }
                }
                catch (Exception ex)
                {
                    Log.Error(ex);
                    throw;
                }
            }
            return retVal;
        }
        public IEnumerable<UserMarketMapping> FdpUserMarketMappingsSave(UserFilter filter)
        {
            IEnumerable<UserMarketMapping> retVal;

            using (var conn = DbHelper.GetDBConnection())
            {
                try
                {
                    var para = new DynamicParameters();
                    para.Add("@CDSId", filter.CDSId, DbType.String);
                    para.Add("@MarketIds", filter.Permissions, DbType.String);
                    para.Add("@CreatorCDSId", CurrentCDSID, DbType.String);

                    retVal = conn.Query<UserMarketMapping>("dbo.Fdp_UserMarkets_Save", para, commandType: CommandType.StoredProcedure);
                }
                catch (Exception ex)
                {
                    Log.Error(ex);
                    throw;
                }
            }
            return retVal;
        }
        public PagedResults<UserDataItem> FdpUserGetMany(UserFilter filter)
        {
            PagedResults<UserDataItem> retVal;

            using (var conn = DbHelper.GetDBConnection())
            {
                try
                {
                    var para = new DynamicParameters();
                    var totalRecords = 0;
                    var totalDisplayRecords = 0;

                    if (!string.IsNullOrEmpty(filter.CDSId))
                    {
                        para.Add("@CDSId", filter.CDSId, DbType.String);
                    }
                    if (!string.IsNullOrEmpty(filter.FilterMessage))
                    {
                        para.Add("@FilterMessage", filter.FilterMessage, DbType.String);
                    }
                    if (filter.HideInactiveUsers.HasValue)
                    {
                        para.Add("@HideInactiveUsers", filter.HideInactiveUsers, DbType.Boolean);
                    }
                    if (filter.PageIndex.HasValue)
                    {
                        para.Add("@PageIndex", filter.PageIndex.Value, DbType.Int32);
                    }
                    if (filter.PageSize.HasValue)
                    {
                        para.Add("@PageSize", filter.PageSize.Value, DbType.Int32);
                    }
                    if (filter.SortIndex.HasValue)
                    {
                        para.Add("@SortIndex", filter.SortIndex.Value, DbType.Int32);
                    }
                    if (filter.SortDirection != SortDirection.NotSet)
                    {
                        var direction = filter.SortDirection == SortDirection.Descending ? "DESC" : "ASC";
                        para.Add("@SortDirection", direction, DbType.String);
                    }
                    para.Add("@TotalPages", dbType: DbType.Int32, direction: ParameterDirection.Output);
                    para.Add("@TotalRecords", dbType: DbType.Int32, direction: ParameterDirection.Output);
                    para.Add("@TotalDisplayRecords", dbType: DbType.Int32, direction: ParameterDirection.Output);

                    var results = conn.Query<UserDataItem>("dbo.Fdp_User_GetMany", para, commandType: CommandType.StoredProcedure);

                    var enumerable = results as IList<UserDataItem> ?? results.ToList();
                    if (enumerable.Any())
                    {
                        totalRecords = para.Get<int>("@TotalRecords");
                        totalDisplayRecords = para.Get<int>("@TotalDisplayRecords");
                    }
                    retVal = new PagedResults<UserDataItem>
                    {
                        PageIndex = filter.PageIndex ?? 1,
                        TotalRecords = totalRecords,
                        TotalDisplayRecords = totalDisplayRecords,
                        PageSize = filter.PageSize ?? totalRecords
                    };

                    var currentPage = enumerable.ToList();

                    retVal.CurrentPage = currentPage;
                }
                catch (Exception ex)
                {
                    Log.Error(ex);
                    throw;
                }
            }

            return retVal;
        }
 public async Task<PagedResults<UserDataItem>> ListUsers(UserFilter filter)
 {
     return await Task.FromResult(_userDataStore.FdpUserGetMany(filter));
 }
        public async Task<IEnumerable<UserRole>> RemoveRole(UserFilter filter)
        {
            var user = await GetUser(filter);

            var roles = user.Roles.ToList();
            var index = roles.FindIndex(r => r == filter.Role);
            if (index != -1)
                roles.RemoveAt(index);

            // Build up a comma seperated list of programme ids and permissions
            filter.Permissions = roles.ToPermissionString();

            return await Task.FromResult(_userDataStore.FdpUserRolesSave(filter));
        }
        public async Task<IEnumerable<UserRole>> AddRole(UserFilter filter)
        {
            var user = await GetUser(filter);

            var roles = user.Roles.ToList();
            var exists = roles.Any(r => r == filter.Role);
            if (!exists)
            {
                roles.Add(filter.Role);
            }
            // Build up a comma seperated list of programme ids and permissions
            filter.Permissions = roles.ToPermissionString();

            return await Task.FromResult(_userDataStore.FdpUserRolesSave(filter));
        }
        public async Task<IEnumerable<UserMarketMapping>> RemoveMarket(UserFilter filter)
        {
            var user = await GetUser(filter);

            var markets = user.Markets.ToList();
            var index = markets.FindIndex(m => m.MarketId == filter.MarketId && m.Action == filter.RoleAction);
            if (index != -1)
                markets.RemoveAt(index);

            // Build up a comma seperated list of programme ids and permissions
            filter.Permissions = markets.ToPermissionString();

            return await Task.FromResult(_userDataStore.FdpUserMarketMappingsSave(filter));
        }
        public async Task<IEnumerable<UserMarketMapping>> AddMarket(UserFilter filter)
        {
            var user = await GetUser(filter);

            var markets = user.Markets.ToList();
            var exists = markets.Any(p => p.MarketId == filter.MarketId && p.Action == filter.RoleAction);
            if (!exists)
            {
                markets.Add(new UserMarketMapping()
                {
                    FdpUserId = user.FdpUserId.GetValueOrDefault(),
                    MarketId = filter.MarketId.GetValueOrDefault(),
                    Action = filter.RoleAction
                });
            }
            // Build up a comma seperated list of programme ids and permissions
            filter.Permissions = markets.ToPermissionString();

            return await Task.FromResult(_userDataStore.FdpUserMarketMappingsSave(filter));
        }
        public async Task<IEnumerable<UserProgrammeMapping>> RemoveProgramme(UserFilter filter)
        {
            var user = await GetUser(filter);

            var programmes = user.Programmes.ToList();
            var index = programmes.FindIndex(p => p.ProgrammeId == filter.ProgrammeId && p.Action == filter.RoleAction);
            if (index != -1)
                programmes.RemoveAt(index);
            
            // Build up a comma seperated list of programme ids and permissions
            filter.Permissions = programmes.ToPermissionString();

            return await Task.FromResult(_userDataStore.FdpUserProgrammeMappingsSave(filter));
        }