package com.oguerreiro.resilient.expression;

import java.math.BigDecimal;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import com.oguerreiro.resilient.domain.EmissionFactor;
import com.oguerreiro.resilient.domain.Period;
import com.oguerreiro.resilient.expression.error.EmissionFactorNotFoundExpressionFunctionException;
import com.oguerreiro.resilient.expression.error.ResilientExpressionFunctionException;
import com.oguerreiro.resilient.repository.EmissionFactorRepository;

/**
 * Base math functions
 */
public class EmissionFactorExpressionFunctions extends MathExpressionFunctions {

  @Autowired
  private EmissionFactorRepository emissionFactorRepository;
  private Integer currentPeriodYear;

  public EmissionFactorExpressionFunctions(Period currentPeriod) {
    this.currentPeriodYear = currentPeriod.getBeginDate().getYear();
  }

  public BigDecimal fe(String emissionFactorCode) throws ResilientExpressionFunctionException {
    // Automatically add the current Period Year.
    return fe(emissionFactorCode, this.currentPeriodYear);
  }

  public BigDecimal fe(String emissionFactorCode, Integer year) throws ResilientExpressionFunctionException {
    List<EmissionFactor> emissionFactors = this.emissionFactorRepository.findByCodeAndYearOrderByYear(
        emissionFactorCode, year);

    if (emissionFactors == null || emissionFactors.isEmpty()) {
      throw new EmissionFactorNotFoundExpressionFunctionException(emissionFactorCode, year);
    }

    return emissionFactors.get(0).getValue();
  }

}
