source("ExternalFunctionsVerification.R")
source("ParametersSetting.R")
source("DietsSetting.R")
source("CategoriesSetting.R")
source("MatrixSetting.R")
source("PlotsSetting.R")

fileCheck <- function(filepath, logger){
  if(!file.exists(filepath)){
    log4r::fatal(logger, paste0("File ", filepath, " does not exist."))
    stop()
  }
  
  if(readxl::excel_format(filepath) != "xlsx"){
    log4r::warn(logger, "Input must be a .xlsx file.")
  }
  
  allShts <- c("ProductionUnit", "Diet", "Category", "Parameters", "Plots")
  sheetNames <- readxl::excel_sheets(path = filepath)
  if(!all(sheetNames %in% allShts)){
    log4r::fatal(logger, paste0("Input file must have sheets named as '", paste0(allShts, collapse = "', '"), "'."))
    stop()
  }
}

readInput <- function(filepath, mtxpath, logger){
  log4r::info(logger, "Initiating input file reading...")
  # TODO check percentage variables to see if its in 0 and 100
  
  resVec <- c()
  
  fileCheck(filepath = filepath, logger = logger)
  
  ProductionUnit <- readDF(filepath = filepath, sht = "ProductionUnit", logger = logger)
  resVec         <- c(resVec, list(ProductionUnit = ProductionUnit))
  
  Parameters <- parametersSetting(filepath = filepath, logger = logger, 
                                  annualMilk = as.numeric(ProductionUnit[ProductionUnit$Information == "annualMilkProd", "Value"]))
  
  Diet   <- dietsSetting(filepath = filepath, logger = logger, pars = Parameters)
  
  cat      <- categoriesSetting(filepath = filepath, logger = logger, diets = Diet, mthnames = Parameters$mthnames)
  Category <- cat$Category
  resVec   <- c(resVec, list(Category = Category))
  
  Parameters[["currentHerd"]] <- cat$currentHerd[order(cat$currentHerd$Category),]
  
  if(cat$currentHerd[cat$currentHerd$Category == "Bull", "Num"] == 0){
    Parameters[["BullsPerCow"]] <- 0
  }
  
  resVec <- c(resVec, list(Diet = Diet))
  
  TransMatrix <- matrixSetting(mtxpath = mtxpath, logger = logger)
  
  if(!is.null(TransMatrix)){
    Plots  <- plotsSetting(filepath = filepath, transMtx = TransMatrix, logger = logger)
    
    if(is.null(Plots)){
      log4r::warn(logger, "Not enough plots information detected. Emissions will not be calculated.")
    }else{
      pltCalcs   <- plotsCalculations(plots = Plots, pars = Parameters)
      Parameters <- c(Parameters, pltCalcs)
      
      resVec <- c(resVec, list(TransMatrix = TransMatrix), list(Plots = Plots))
    }
  }
  
  resVec <- c(resVec, Parameters)
  
  log4r::info(logger, "Inputs reading completed.")
  
  return(resVec)
}
