using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace Model.Managers
{
///
/// The Main manager of the model.
///
public class MasterManager
{
#region Attributes & Properties
///
/// The currently connected user. 'null' if no user is connected.
///
public User? CurrentConnectedUser { get; private set; }
///
/// The collection of all recipes loaded.
///
public RecipeCollection Recipes { get; private set; }
///
/// The collection of all users loaded.
///
public List Users { get; private set; }
///
/// The data manager for load, save, export and import data.
///
public DataManager DataMgr { get; private set; }
#endregion
#region Constructors
///
/// Constructor of the MasterManager.
///
/// The serializer for the data.
public MasterManager(IDataManager dataManager)
{
DataMgr = new DataManager(dataManager);
CurrentConnectedUser = null;
Recipes = DataMgr.GetRecipes("all recipes");
Users = DataMgr.GetUsers();
}
#endregion
#region Methods
///
/// Log in an user. Test if the log in information are correct then connect the user.
///
/// The user's mail
/// The user's password.
/// True if the user was correctly connected, false if there is something wrong.
///
public bool Login(string mail, string password)
{
if (Users is null || Users.Count == 0)
throw new ArgumentNullException("There is no users registred.");
if (mail == "admin")
{
CurrentConnectedUser = Users.FirstOrDefault(u => u.Mail == "admin@mctg.fr");
return true;
}
User? user = Users.Find(u => u.Mail == mail);
if (user is null || !user.psswMgr.VerifyPassword(user.Password, password))
return false;
CurrentConnectedUser = user;
return true;
}
///
/// Log out an user.
///
/// True if the user is correctly diconnected, false otherwise.
public bool Logout()
{
if (CurrentConnectedUser is null)
return false;
CurrentConnectedUser = null;
return true;
}
///
/// Register an user.
///
/// The new user to add in the database.
/// False if there is a problem with the registerement, true otherwise.
public bool Register(User newuser)
{
try
{
User user = newuser;
DataMgr.Data[nameof(User)].Add(user);
Users = DataMgr.GetUsers();
}
catch (ArgumentException e)
{
Debug.WriteLine(e.Message);
return false;
}
return true;
}
///
/// Add a recipe to the database.
///
/// The recipe to add.
public void AddRecipe(Recipe recipe)
{
DataMgr.Data[nameof(Recipe)].Add(recipe);
Recipes = DataMgr.GetRecipes();
}
///
/// Get the current connected user's personal recipes.
///
/// The current connected user's personal recipes.
public RecipeCollection GetCurrentUserRecipes()
=> new RecipeCollection("User recipes",
DataMgr.GetRecipes().FindAll(r => r.AuthorMail == CurrentConnectedUser?.Mail).ToArray());
}
#endregion
}