using System; using System.Collections.Generic; using MySqlConnector; using WebApplication.Modules; using WebApplication.Repositorys.Interfaces; namespace WebApplication.Repositorys { public class CustomerRepository : ICustomerRepository { private string GetFreeId() { string guid = Guid.NewGuid().ToString(); while (true) { if (GetCustomer(guid) is not null) guid = Guid.NewGuid().ToString(); else break; } return guid; } public Customer AddCustomer(CustomerEditor editor) { Customer customer = new Customer {Guid = GetFreeId(), CreationDate = DateTime.Now}; editor.EditCustomer(customer); SaveCustomer(customer); return customer; } public void RemoveCustomer(string id) { MySQL.Insert($"DELETE FROM Customers WHERE Guid = \"{id}\""); } public void EditCustomer(string id, CustomerEditor editor) { RemoveCustomer(id); Customer customer = GetCustomer(id); editor.EditCustomer(customer); SaveCustomer(customer); } public Customer GetCustomer(string id) { MySqlDataReader reader = MySQL.GetData($"SELECT * FROM Customers WHERE Guid = \"{id}\""); if (reader.Read()) { Customer customer = new Customer(); customer.Guid = reader.GetString("Guid"); customer.CreationDate = DateTime.Parse(reader.GetString("CreationDate")); customer.FirstName = reader.GetString("FirstName"); customer.LastName = reader.GetString("LastName"); customer.Email = reader.GetString("Email"); customer.Username = reader.GetString("Username"); customer.Password = reader.GetString("Password"); customer.Balance = float.Parse(reader.GetString("Balance")); reader.Close(); return customer; } reader.Close(); return null; } public IEnumerable GetCustomers() { List customers = new List(); MySqlDataReader reader = MySQL.GetData("SELECT * FROM Customers"); while (reader.Read()) { Customer customer = new Customer(); customer.Guid = reader.GetString("Guid"); customer.CreationDate = DateTime.Parse(reader.GetString("CreationDate")); customer.FirstName = reader.GetString("FirstName"); customer.LastName = reader.GetString("LastName"); customer.Email = reader.GetString("Email"); customer.Username = reader.GetString("Username"); customer.Balance = float.Parse(reader.GetString("Balance")); customers.Add(customer); } reader.Close(); return customers; } private void SaveCustomer(Customer customer) { MySQL.Insert($"INSERT INTO Customers VALUES (\"{customer.Guid}\", \"{customer.CreationDate}\", \"{customer.FirstName}\", \"{customer.LastName}\", \"{customer.Email}\", \"{customer.Username}\", \"{customer.Password}\", \"{customer.Balance}\")"); } } }