using AutoMapper; using Microsoft.EntityFrameworkCore; using SessionCompanion.Database.Repositories.Base; using SessionCompanion.Database.Tables; using SessionCompanion.Extensions.EitherType; using SessionCompanion.Services.Base; using SessionCompanion.Services.Interfaces; using SessionCompanion.ViewModels.ApiResponses; using SessionCompanion.ViewModels.ShopkeeperViewModels; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SessionCompanion.Services.Services { public class ShopkeeperService : ServiceBase, IShopkeeperService { public ShopkeeperService(IMapper mapper, IRepository repository) : base(mapper, repository) { } /// /// Funkcja zmienia status sprzedawcy /// /// /// /// SuccesResponse/ErrorResponse public async Task> ChangeShopkeeperStatus(int shopkeeperId, bool availability) { try { var shopkeepers = await Repository.Get().ToListAsync(); if (availability) { foreach (var shopkeeper in shopkeepers) { if (shopkeeper.Id.Equals(shopkeeperId)) shopkeeper.IsAvailable = true; else shopkeeper.IsAvailable = false; await Repository.Update(shopkeeper); } await Repository.Save(); return new SuccessResponse("Shopkeepers updated") { SuccessCode = 200 }; } var newActiveShopkeeper = shopkeepers.Where(c => c.Id.Equals(shopkeeperId)).Single(); newActiveShopkeeper.IsAvailable = false; await Repository.Update(newActiveShopkeeper); await Repository.Save(); return new SuccessResponse("Shopkeepers updated") { SuccessCode = 200 }; } catch (Exception e) { return new ErrorResponse() { StatusCode = 500, Message = e.Message }; } } public async Task> CreateNewShopKeeper(ShopkeeperWithItemsViewModel shopkeeperWithItemsViewModel) { try { var activeShopkeeper = await Repository.Get(c => c.IsAvailable.Equals(true)).SingleAsync(); if (activeShopkeeper != null && shopkeeperWithItemsViewModel.IsAvailable) { activeShopkeeper.IsAvailable = false; await Repository.Update(activeShopkeeper); } var result = Mapper.Map(shopkeeperWithItemsViewModel); await Repository.Create(result); await Repository.Save(); return new SuccessResponse("New shopkeeper created"); } catch (Exception e) { return new ErrorResponse() { StatusCode = 500, Message = e.Message }; } } public async Task> GetActiveShkopkeeperWithItems() { try { var activeShopkeeper = await Repository.Get(c => c.IsAvailable.Equals(true)) .Include(t => t.ShopkeeperItems) .ThenInclude(t => t.Armor) .Include(t => t.ShopkeeperItems) .ThenInclude(t => t.Weapon).SingleAsync(); var result = Mapper.Map(activeShopkeeper); return result; } catch (Exception e) { return new ErrorResponse() { StatusCode = 500, Message = e.Message }; } } } }