AverageCowHealthService.java

  1. package edu.ucsb.cs156.happiercows.services;

  2. import org.springframework.beans.factory.annotation.Autowired;
  3. import org.springframework.stereotype.Service;

  4. import edu.ucsb.cs156.happiercows.entities.UserCommons;
  5. import edu.ucsb.cs156.happiercows.repositories.UserCommonsRepository;

  6. @Service
  7. public class AverageCowHealthService {

  8.     @Autowired
  9.     private UserCommonsRepository userCommonsRepository;

  10.     public Double getAverageCowHealth(Long commonsId) {
  11.         Iterable<UserCommons> userCommonsList = userCommonsRepository.findByCommonsId(commonsId);
  12.         Double totalHealth = 0.0;
  13.         int totalCows = 0;

  14.         for(UserCommons userCommons: userCommonsList){
  15.             totalHealth += userCommons.getCowHealth() * userCommons.getNumOfCows();
  16.             totalCows += userCommons.getNumOfCows();
  17.         }

  18.         if(!userCommonsList.iterator().hasNext()){
  19.             throw new IllegalArgumentException("Unable to get average cow health");
  20.         }

  21.         return totalCows == 0 ? 0 :totalHealth / totalCows;
  22.     }
  23. }