/// <summary>
        /// Takes a ManageUsersProfileVM as arguement which contain permission model: Return a list of RoleName that were set to true.
        /// </summary>
        /// <param name="ConvertToRoleNames"></param>
        /// <returns></returns>
        public static List<string> ConvertToRoleNames(ManageUsersProfileVM model)
        {
            List<string> myRoles = new List<string>();


            if (model.permission.permission.News == true)
            {
                myRoles.Add("News");
            }
            if (model.permission.permission.Accesscontrol == true)
            {
                myRoles.Add("AccessControl");
            }
            if (model.permission.permission.Delivery == true)
            {
                myRoles.Add("Delivery");
            }
            if (model.permission.permission.Events == true)
            {
                myRoles.Add("Events");
            }
            if (model.permission.permission.LegalDocs == true)
            {
                myRoles.Add("LegalDocs");
            }
            if (model.permission.permission.Repair == true)
            {
                myRoles.Add("Repair");
            }
            if (model.permission.permission.BasicFeatures == true)
            {
                myRoles.Add("BasicFeatures");
            }
            if (model.permission.permission.Apartment == true)
            {
                myRoles.Add("Apartment");
            }
            if (model.permission.permission.Contactbook == true)
            {
                myRoles.Add("Contactbook");
            }


            return myRoles;
        }
        public ActionResult ManageUsersProfile(int BuildingID)
        {
            //todo: create users, assign level of privilage
            ManageUsersProfileVM mupvm = new ManageUsersProfileVM();
           var result= mupvm.InsertRole("Repair1");

           return View(mupvm);
        }
 public ActionResult Loadingbuildinguserpermissions(string BuildingIDUserID)
 {
     ManageUsersProfileVM Objbu = new ManageUsersProfileVM();
    var BuildingUserpermissions = Objbu.LoadBuildingUserPermission(BuildingIDUserID);
    return new JsonResult { Data = BuildingUserpermissions, JsonRequestBehavior = JsonRequestBehavior.AllowGet };   
    
 }
        public async Task<ActionResult> EditBUPermissions(int BuildingID, PermissionBase permission, ManageUsersProfileVM model, string UserID)
        {
            
            ManageUsersProfileVM ObjBU = new ManageUsersProfileVM();
           

            var RoleNames = ObjBU.ConvertToRoleNames(permission);
            await ObjBU.EditbuildingUserPermission(RoleNames, UserID);
            return RedirectToAction("ManageUsersProfile", new { BuildingID = BuildingID });
        }
       public JsonResult AddUser(int BuildingID, ManagerVM model_User, PermissionBase Permission, ManageUsersProfileVM model4)
        {
            ManageUsersProfileVM Obj = new ManageUsersProfileVM();
            model4.managerVM = model_User;
         
            Obj.managerVM = model_User;
            var UserID = Obj.InsertUser(Obj);  //Create a user to the mail aspNetUser table.         
            var RoleNames = Obj.ConvertToRoleNames(Permission);//Pass all permissions and return a list type string of accepted roles
          var returnUserID = Obj.AddBuildingUser(model_User, UserID);// Insert building staff.
            foreach (var item in RoleNames)// loop throught the list of roles
            {
                Obj.InserUserPermission(item, returnUserID); // Insert one permission at a time. 
            }


            var mydata = Json("");
            return new JsonResult {Data = mydata, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
        }
 public ActionResult ManageUsersProfile(int BuildingID)
  {
      //todo: create users, assign level of privilage
      ManageUsersProfileVM mupvm = new ManageUsersProfileVM();
      mupvm.BuildingID = BuildingID;
      ViewBag.BuildingUsers = mupvm.LoadBuildingUsers(BuildingID);
      ViewBag.BuildingInfo = db.Buildings.Find(BuildingID);
     return View(mupvm);
  }
        private async Task<string> CreatUserdb(ManageUsersProfileVM modelManagementVM)
        {

            try
            {
                
                ApplicationDbContext context = new ApplicationDbContext();

                var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
                PasswordHasher hasher = new PasswordHasher();
                var a = UserManager.FindByEmail(modelManagementVM.managerVM.Email);
                if (a != null)
                {
                    return "";
                }
                ApplicationUser AppUser = new ApplicationUser()
                {
                    Id = Guid.NewGuid().ToString(),
                    Email = modelManagementVM.managerVM.Email,
                    UserName = modelManagementVM.managerVM.Username,
                    SecurityStamp = Guid.NewGuid().ToString(),
                    PhoneNumber = modelManagementVM.managerVM.Phone,
                    LockoutEnabled = false,
                    LockoutEndDateUtc = DateTime.Now.AddDays(365),
                    AccessFailedCount = 0,
                    PhoneNumberConfirmed = false,
                    TwoFactorEnabled = false,
                    EmailConfirmed = false,
                    PasswordHash = hasher.HashPassword(modelManagementVM.managerVM.Password)
                };
                string[] FullName = modelManagementVM.managerVM.FullName.Split(new string[] { " " }, StringSplitOptions.None);
                Manager mgr = new Manager()
                {
                    ID = AppUser.Id,
                    FirstName = FullName[0].ToString(),
                    LastName = FullName[1].ToString(),
                    Phone = modelManagementVM.managerVM.Phone,
                    ClientID = modelManagementVM.managerVM.clientID
                };
                PermissionMapRole ObjPerm = new PermissionMapRole() {
                    UserID = AppUser.Id,
                    //RoleID =  TODO!!!!      
                };
                

                db.Manager.Add(mgr);
                context.Users.Add(AppUser);

                await context.SaveChangesAsync();
                await db.SaveChangesAsync();    

                var RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
                if (!RoleManager.RoleExists("Manager"))
                { var roleresult = RoleManager.Create(new IdentityRole("Manager")); }
                var Result = UserManager.AddToRole(AppUser.Id, "Manager");

                ManagerBuilding ObjManagerBuilding = new ManagerBuilding()
                {
                    BuildingID = modelManagementVM.managerVM.BuildingID,
                    ManagerID = mgr.ID,
                    UserID = mgr.ID
                };

                db.ManagerBuilding.Add(ObjManagerBuilding);
                await db.SaveChangesAsync();


            }
            catch (DbEntityValidationException e)
            {
                foreach (var eve in e.EntityValidationErrors)
                {
                    Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
                        eve.Entry.Entity.GetType().Name, eve.Entry.State);
                    foreach (var ve in eve.ValidationErrors)
                    {
                        Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
                            ve.PropertyName, ve.ErrorMessage);
                    }
                }
                throw;
            }
            return ""; 
        }
 public string CreatUser(ManageUsersProfileVM model)
 {
     var result = CreatUserdb(model);
     return result.ToString();
 }
        private string InsertUserdb(ManageUsersProfileVM model)
        {
            try
            {
                ApplicationDbContext context = new ApplicationDbContext();

                var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
                PasswordHasher hasher = new PasswordHasher();
                var a = UserManager.FindByEmail(model.managerVM.Email);
                if (a != null)
                {
                    return "";
                }
                ApplicationUser AppUser = new ApplicationUser()
                {
                    Id = Guid.NewGuid().ToString(),
                    Email = model.managerVM.Email,
                    UserName = model.managerVM.Username,
                    SecurityStamp = Guid.NewGuid().ToString(),
                    PhoneNumber = model.managerVM.Phone,
                    LockoutEnabled = false,
                    LockoutEndDateUtc = DateTime.Now.AddDays(365),
                    AccessFailedCount = 0,
                    PhoneNumberConfirmed = false,
                    TwoFactorEnabled = false,
                    EmailConfirmed = false,
                    PasswordHash = hasher.HashPassword(model.managerVM.Password)
                };
                string[] FullName = model.managerVM.FullName.Split(new string[] { " " }, StringSplitOptions.None);
               
                context.Users.Add(AppUser);
                 context.SaveChangesAsync();
                

                 return AppUser.Id;

            }
            catch (DbEntityValidationException e)
            {
                foreach (var eve in e.EntityValidationErrors)
                {
                    Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
                        eve.Entry.Entity.GetType().Name, eve.Entry.State);
                    foreach (var ve in eve.ValidationErrors)
                    {
                        Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
                            ve.PropertyName, ve.ErrorMessage);
                    }
                }
                throw;
            }
          
        }
        public async Task<ActionResult> BuildingProfile(int? page, string search, int BuildingID)
        {

            ManageUsersProfileVM ObjBU = new ManageUsersProfileVM();
            List<BuildingUser> ListBU = ObjBU.LoadBuildingUsers(BuildingID);
            ViewBag.BuildingUsers = ListBU;
            ViewBag.ClientName = db.Buildings.Find(BuildingID).Clients.ClientName;
           
            ViewBag.Manager = db.ManagerBuilding
               .Where(c => c.BuildingID == BuildingID)
               .Select(c => new ManagerVM
               {
                   FullName = c.Manager.FirstName + " " + c.Manager.LastName,
                   Username = c.Manager.AspNetUsers.Email,
                   Phone = c.Manager.Phone
               }).FirstOrDefault();

            Session.Timeout = 20;

            ViewBag.BuildingID = BuildingID;

            //Module
            ViewBag.Module = db.Module.Where(m => m.BuildingID == BuildingID).ToList();
            ViewBag.ModuleCount = db.Module.Where(model => model.BuildingID == BuildingID).Count();

                        var buildinginfo = await db.Buildings
                  .Where(c => c.ID == BuildingID)
                  .Select(c => new BuildingInfoVM
                  {
                      ID = c.ID,
                      BuildingName = c.BuildingName,
                      BuildingPhone = c.BuildingPhone,
                      Address = c.Address,
                      City = c.City,
                      ZipCode = c.Zipcode,
                      Manager = c.Manager,
                      ClientID = c.Clients.ID,                     
                      States = c.State
                  }).FirstAsync();
            Session["Building"] = buildinginfo;
            ViewBag.buildingInfo = buildinginfo;


            //=================building profile appartmentlist==========================================
            if (page == null  && search != null)
            {
               
                ViewBag.search = search;
            }
            if (page != null && search != null)
            {
               
                ViewBag.search = search;
            }
            if (Request.HttpMethod != "GET")
            {
                page = 1; // after post reset page to 1

            }
            int pageSize = 96;
            int pageNumber = (page ?? 1);

            if (search !=null)
            {
                //executes when there is a search
                var apartmentlist = await db.Apartment
               .Where(c => c.BuildingID == BuildingID && c.ApartmentNumber.Contains(search))
               .Select(c => new ApartmentVM
               {
                   ID = c.ID,
                   ApartmentNumber = c.ApartmentNumber

               }).ToListAsync();
                ViewBag.apartmentlist = apartmentlist.ToPagedList(pageNumber, pageSize);
            }
            else
            {
                //executes when there is no search
                var apartmentlist = await db.Apartment
                    .Where(c => c.BuildingID == BuildingID)
                    .Select(c => new ApartmentVM
                    {
                        ApartmentNumber = c.ApartmentNumber,
                        ID = c.ID

                    }).ToListAsync();
                ViewBag.apartmentlist = apartmentlist.ToPagedList(pageNumber, pageSize);

            }

            //loading Activemanager
            var Activemanager = db.ActiveManager.Where(c => c.BuildingID == BuildingID)
                                                     .Select(c => new ActiveManagerVM
                                                     {
                                                         Id = c.Id,
                                                         BuildingID = c.BuildingID,
                                                         ManagerID = c.ManagerID
                                                     }).FirstOrDefault();
            if (Activemanager != null)
            {
                Activemanager.myManager = db.Manager.Find(Activemanager.ManagerID);
            }

            ViewBag.Activemanager = Activemanager;

           

            

            return View( );
        }