add suggestion button, fix priority persistence

pull/56/head
Alexandre AGOSTINHO 2 years ago
parent 3b2101f2fe
commit e87ddf566a

@ -56,7 +56,7 @@ namespace Managers
public RecipeCollection SearchRecipeByTitle(string title) public RecipeCollection SearchRecipeByTitle(string title)
{ {
IEnumerable<Recipe> recipes = from Recipe recipe in _dataManager.GetFromData<Recipe>() IEnumerable<Recipe> recipes = from Recipe recipe in _dataManager.GetFromData<Recipe>()
where recipe.Title.Contains(title) where recipe.Title.ToLower().Contains(title.ToLower())
select recipe; select recipe;
return new RecipeCollection( return new RecipeCollection(
$"Search for '{title}'", recipes.ToArray()); $"Search for '{title}'", recipes.ToArray());

@ -1,32 +1,32 @@
using AppException; using AppException;
using Model; using Model;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
using System.Diagnostics; using System.Diagnostics;
using System.Linq; using System.Linq;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
using System.Security.Cryptography; using System.Security.Cryptography;
using System.Text; using System.Text;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace Managers namespace Managers
{ {
public class UserDefaultManager : IUserManager, INotifyPropertyChanging public class UserDefaultManager : IUserManager, INotifyPropertyChanging
{ {
private IDataManager _dataManager; private IDataManager _dataManager;
private IPasswordManager _passwordManager; private IPasswordManager _passwordManager;
private User? _currentConnected = null; private User? _currentConnected = null;
public UserDefaultManager(IDataManager dataManager, IPasswordManager passwordManager) public UserDefaultManager(IDataManager dataManager, IPasswordManager passwordManager)
{ {
_dataManager = dataManager; _dataManager = dataManager;
_passwordManager = passwordManager; _passwordManager = passwordManager;
} }
public User? CurrentConnected public User? CurrentConnected
{ {
get => _currentConnected; get => _currentConnected;
@ -35,115 +35,115 @@ namespace Managers
_currentConnected = value; _currentConnected = value;
OnPropertyChanged(); OnPropertyChanged();
} }
} }
public IPasswordManager PasswordManager => _passwordManager; public IPasswordManager PasswordManager => _passwordManager;
public event PropertyChangingEventHandler? PropertyChanging; public event PropertyChangingEventHandler? PropertyChanging;
public void OnPropertyChanged([CallerMemberName] string pname = "") public void OnPropertyChanged([CallerMemberName] string pname = "")
=> PropertyChanging?.Invoke(this, new PropertyChangingEventArgs(pname)); => PropertyChanging?.Invoke(this, new PropertyChangingEventArgs(pname));
public bool AddUserToData(User user) public bool AddUserToData(User user)
{ {
var userList = _dataManager.Data[nameof(User)]; var userList = _dataManager.Data[nameof(User)];
if (userList.Exists(r => r.Equals(user))) if (userList.Exists(r => r.Equals(user)))
return false; return false;
_dataManager.Data[nameof(User)].Add(user); _dataManager.Data[nameof(User)].Add(user);
return true; return true;
} }
public User CreateUser(string mail, string password, public User CreateUser(string mail, string password,
string? name = null, string? surname = null, string? profilePict = null) string? name = null, string? surname = null, string? profilePict = null)
{ {
if (name is null) name = $"user{GetRandomInt()}"; if (name is null) name = $"user{GetRandomInt()}";
if (surname is null) surname = ""; if (surname is null) surname = "";
if (profilePict is null) profilePict = "default_user_picture.png"; if (profilePict is null) profilePict = "default_user_picture.png";
const string mailRegex = @"^([\w\.-]+)@([\w\.-]+\.\w+)$"; const string mailRegex = @"^([\w\.-]+)@([\w\.-]+\.\w+)$";
if (!Regex.Match(mail, mailRegex).Success) if (!Regex.Match(mail, mailRegex).Success)
throw new BadMailFormatException(); throw new BadMailFormatException();
string hashedPassword = PasswordManager.HashPassword(password); string hashedPassword = PasswordManager.HashPassword(password);
return new User(name, surname, mail, hashedPassword, profilePict); return new User(name, surname, mail, hashedPassword, profilePict);
} }
public ICollection<User> GetAllUsers() public ICollection<User> GetAllUsers()
{ {
return _dataManager.GetFromData<User>(); return _dataManager.GetFromData<User>();
} }
public User GetUserFromMail(string mail) public User GetUserFromMail(string mail)
{ {
User? user = _dataManager.GetFromData<User>().ToList() User? user = _dataManager.GetFromData<User>().ToList()
.Find(u => u.Mail == mail); .Find(u => u.Mail == mail);
if (user is null) if (user is null)
throw new UserNotFoundException(); throw new UserNotFoundException();
return user; return user;
} }
public bool LogIn(string mail, string password) public bool LogIn(string mail, string password)
{ {
if (CurrentConnected is not null) if (CurrentConnected is not null)
throw new UserAlreadyConnectedException(); throw new UserAlreadyConnectedException();
#if DEBUG #if DEBUG
if (mail == "admin") if (mail == "admin")
{ {
CurrentConnected = _dataManager.GetFromData<User>() CurrentConnected = _dataManager.GetFromData<User>()
.FirstOrDefault(u => u.Mail == "admin@mctg.fr"); .FirstOrDefault(u => u.Mail == "admin@mctg.fr");
return true; return true;
} }
#endif #endif
User? user = _dataManager.GetFromData<User>().ToList() User? user = _dataManager.GetFromData<User>().ToList()
.Find(u => u.Mail == mail); .Find(u => u.Mail == mail);
if (user is null) if (user is null)
return false; return false;
if (!_passwordManager.VerifyPassword(user.Password, password)) if (!_passwordManager.VerifyPassword(user.Password, password))
return false; return false;
CurrentConnected = user; CurrentConnected = user;
return true; return true;
} }
public void LogOut() public void LogOut()
{ {
if (CurrentConnected is null) if (CurrentConnected is null)
throw new NoUserConnectedException(); throw new NoUserConnectedException();
CurrentConnected = null; CurrentConnected = null;
} }
public bool ModifyCurrentConnected(User newUser) public bool ModifyCurrentConnected(User newUser)
{ {
try try
{ {
var index = _dataManager.GetFromData<User>().ToList() var index = _dataManager.GetFromData<User>().ToList()
.FindIndex(u => u.Equals(CurrentConnected)); .FindIndex(u => u.Equals(CurrentConnected));
_dataManager.Data[nameof(User)][index] = newUser; _dataManager.Data[nameof(User)][index] = newUser;
} }
catch (ArgumentNullException e) catch (ArgumentNullException e)
{ {
Debug.WriteLine("User to modify not found.\n" + e.Message); Debug.WriteLine("User to modify not found.\n" + e.Message);
return false; return false;
} }
return true; return true;
} }
private int GetRandomInt() private int GetRandomInt()
{ {
var randomGenerator = RandomNumberGenerator.Create(); var randomGenerator = RandomNumberGenerator.Create();
byte[] data = new byte[16]; byte[] data = new byte[16];
randomGenerator.GetBytes(data); randomGenerator.GetBytes(data);
return Math.Abs(BitConverter.ToInt16(data)); return Math.Abs(BitConverter.ToInt16(data));
} }
} }
} }

@ -17,7 +17,7 @@ namespace Model
/// <br/><remarks><i>The setter is actually public for testing purpose. It will be private after.</i></remarks> /// <br/><remarks><i>The setter is actually public for testing purpose. It will be private after.</i></remarks>
/// <br/>See: <see cref="IDataSerializer"/> /// <br/>See: <see cref="IDataSerializer"/>
/// </summary> /// </summary>
IDataSerializer Serializer { get; } IDataSerializer Serializer { get; set; }
/// <summary> /// <summary>
/// The collection of all data. Each line of this dictionary has the type of the data as it key and the data for values. /// The collection of all data. Each line of this dictionary has the type of the data as it key and the data for values.

@ -14,12 +14,12 @@ namespace Model
public class User : IEquatable<User> , INotifyPropertyChanged public class User : IEquatable<User> , INotifyPropertyChanged
{ {
#region Private Attributes #region Private Attributes
[DataMember] private string _name = ""; [DataMember(Name = "name")] private string _name = "";
[DataMember] private string _surname = ""; [DataMember(Name = "surname")] private string _surname = "";
[DataMember] private string _mail = ""; [DataMember(Name = "mail")] private string _mail = "";
[DataMember(Name = "priorities")] [DataMember(Name = "priorities")]
public ObservableCollection<Priority> _priorities { get; private set; } = new ObservableCollection<Priority> private readonly List<Priority> _priorities = new List<Priority>
{ {
Priority.Gourmet, Priority.Gourmet,
Priority.Economic, Priority.Economic,
@ -28,7 +28,9 @@ namespace Model
Priority.Easy Priority.Easy
}; };
public event PropertyChangedEventHandler? PropertyChanged;
public event PropertyChangedEventHandler? PropertyChanged;
#endregion #endregion
#region Properties #region Properties
@ -98,7 +100,7 @@ namespace Model
/// This is the list of priorities specific tu the user. This list is initiate /// This is the list of priorities specific tu the user. This list is initiate
/// by default. User could change it at will. /// by default. User could change it at will.
/// </summary> /// </summary>
public ReadOnlyObservableCollection<Priority> Priorities { get; private set; } public List<Priority> Priorities => _priorities;
#endregion #endregion
#region Methods #region Methods
@ -150,7 +152,7 @@ namespace Model
Surname = surname; Surname = surname;
Mail = mail; Mail = mail;
Password = hashedPassword; Password = hashedPassword;
Priorities = new ReadOnlyObservableCollection<Priority>(_priorities);
} }
/// <inheritdoc cref="User.User"/> /// <inheritdoc cref="User.User"/>
@ -176,7 +178,6 @@ namespace Model
Mail = user.Mail; Mail = user.Mail;
Password = user.Password; Password = user.Password;
_priorities = user._priorities; _priorities = user._priorities;
Priorities = new ReadOnlyObservableCollection<Priority>(_priorities);
ProfilePict = user.ProfilePict; ProfilePict = user.ProfilePict;
} }
#endregion #endregion

@ -177,7 +177,6 @@ namespace FakePersistance
surname: "Amigos", surname: "Amigos",
mail: "pedrosamigos@hotmail.com", mail: "pedrosamigos@hotmail.com",
hashedPassword: psswdMgr.HashPassword("pamigos")) hashedPassword: psswdMgr.HashPassword("pamigos"))
}) })
#endregion #endregion
} }

@ -42,9 +42,7 @@ namespace Views
// Change the data serializer if the one in place is 'Stubs' // Change the data serializer if the one in place is 'Stubs'
if (Master.Data.Serializer.GetType() == typeof(Stubs)) if (Master.Data.Serializer.GetType() == typeof(Stubs))
{ {
var data = Master.Data.Data; Master.Data.Serializer = dataSerializer;
dataManager = new DataDefaultManager(dataSerializer, data);
Master = new MasterManager(dataManager, recipeManager, userManager);
} }
// Save data. // Save data.

@ -25,6 +25,12 @@
SearchButtonPressed="SearchBar_SearchButtonPressed"/> SearchButtonPressed="SearchBar_SearchButtonPressed"/>
<!-- Direct research --> <!-- Direct research -->
<Button
Text="Suggestions"
ImageSource="home_icon.png"
Style="{StaticResource button1}"
Clicked="Suggestions_Clicked"
IsVisible="{Binding IsConnected, Source={x:Reference container_base}}"/>
<Button <Button
Text="Toutes les recettes" Text="Toutes les recettes"
ImageSource="home_icon.png" ImageSource="home_icon.png"

@ -1,4 +1,5 @@
using Model; using AppException;
using Model;
using System.Collections.ObjectModel; using System.Collections.ObjectModel;
namespace Views namespace Views
@ -9,12 +10,18 @@ namespace Views
private readonly RecipeCollection _recipesDisplayed; private readonly RecipeCollection _recipesDisplayed;
public ReadOnlyObservableRecipeCollection RecipesDisplayed { get; private set; } public ReadOnlyObservableRecipeCollection RecipesDisplayed { get; private set; }
public string Description => _recipesDisplayed.Description;
public Home() public Home()
{ {
Master.User.LogIn("admin", "");
_recipesDisplayed = Master.Recipe.GetAllRecipes(); _recipesDisplayed = Master.Recipe.GetAllRecipes();
if (Master.User.CurrentConnected is null)
_recipesDisplayed.Description = "Toutes les recettes";
else
_recipesDisplayed.Description = "Suggestions";
RecipesDisplayed = new ReadOnlyObservableRecipeCollection(_recipesDisplayed); RecipesDisplayed = new ReadOnlyObservableRecipeCollection(_recipesDisplayed);
InitializeComponent(); InitializeComponent();
@ -39,6 +46,7 @@ namespace Views
string searchStr = (sender as SearchBar).Text; string searchStr = (sender as SearchBar).Text;
ModifyRecipesDisplayed(Master.Recipe.SearchRecipeByTitle(searchStr)); ModifyRecipesDisplayed(Master.Recipe.SearchRecipeByTitle(searchStr));
} }
public void OnImageClicked(object sender, EventArgs e) public void OnImageClicked(object sender, EventArgs e)
{ {
Master.Recipe.CurrentSelected = (Recipe)(sender as ImageButton).BindingContext; Master.Recipe.CurrentSelected = (Recipe)(sender as ImageButton).BindingContext;
@ -74,7 +82,17 @@ namespace Views
private void AllRecipes_Clicked(object sender, EventArgs e) private void AllRecipes_Clicked(object sender, EventArgs e)
{ {
ModifyRecipesDisplayed(Master.Recipe.GetAllRecipes()); ModifyRecipesDisplayed(new RecipeCollection("Toutes les recettes", Master.Recipe.GetAllRecipes()));
}
private void Suggestions_Clicked(object sender, EventArgs e)
{
if (Master.User.CurrentConnected is null)
throw new NoUserConnectedException();
ModifyRecipesDisplayed(new RecipeCollection(
description: "Suggestions",
recipes: Master.Recipe.GetRecipesByPriorityOrder(Master.User.CurrentConnected.Priorities)));
} }
} }
} }

Loading…
Cancel
Save