pet-companion-back/Services/PetSkillService.cs

90 lines
3.3 KiB
C#

using PetCompanion.Models;
using PetCompanion.Repositories;
namespace PetCompanion.Services
{
public class PetSkillService
{
private readonly PetSkillRepository _petSkillRepository;
private readonly PetRepository _petRepository;
public PetSkillService(PetSkillRepository petSkillRepository, PetRepository petRepository)
{
_petSkillRepository = petSkillRepository;
_petRepository = petRepository;
}
public IEnumerable<PetSkill> GetPetSkills(string petId, string userId)
{
var pet = _petRepository.GetPetById(petId, userId);
if (pet == null)
throw new Exception("Pet not found");
return _petSkillRepository.GetPetSkills(petId);
}
public PetSkill UpgradeSkill(string petId, string userId, int skillId)
{
var pet = _petRepository.GetPetById(petId, userId);
if (pet == null)
throw new Exception("Pet not found");
var skill = _petSkillRepository.GetSkill(skillId);
if (skill == null)
throw new Exception("Skill not found");
foreach (var req in skill.SkillRequirements)
{
if (req.Resource.ToLower() == "wisdom" && pet.Resources.Wisdom < req.Cost)
throw new Exception("Insufficient resources");
if (req.Resource.ToLower() == "food" && pet.Resources.Food < req.Cost)
throw new Exception("Insufficient resources");
if (req.Resource.ToLower() == "gold" && pet.Resources.Gold < req.Cost)
throw new Exception("Insufficient resources");
if (req.Resource.ToLower() == "junk" && pet.Resources.Junk < req.Cost)
throw new Exception("Insufficient resources");
}
var skills = _petSkillRepository.GetPetSkills(petId);
var existingSkill = skills.FirstOrDefault(s => s.SkillId == skillId);
if (existingSkill != null)
{
if (existingSkill.CurrentTier == SkillTier.III)
throw new Exception("Skill already at maximum tier");
existingSkill.CurrentTier++;
_petSkillRepository.SavePetSkill(existingSkill);
}
else
{
if (!skill.SkillsIdRequired?.TrueForAll(ni => pet.Skills.Any(s => s.SkillId == ni)) ?? false)
{
throw new Exception("Missing required skill");
}
existingSkill = new PetSkill
{
PetId = petId,
SkillId = skillId,
CurrentTier = SkillTier.I
};
_petSkillRepository.SavePetSkill(existingSkill);
}
foreach (var req in skill.SkillRequirements)
{
if (req.Resource.ToLower() == "wisdom") pet.Resources.Wisdom -= req.Cost;
if (req.Resource.ToLower() == "food") pet.Resources.Food -= req.Cost;
if (req.Resource.ToLower() == "gold") pet.Resources.Gold -= req.Cost;
if (req.Resource.ToLower() == "junk") pet.Resources.Junk -= req.Cost;
}
_petRepository.UpdatePet(pet);
return existingSkill;
}
}
}