package com.capgemini.reports.optimized.r24report;

import com.capgemini.reports.exceptions.InvalidUserInputException;
import com.capgemini.reports.exceptions.UserInputErrorEnum;
import com.capgemini.reports.optimized.OptimizedFile;
import com.capgemini.reports.reports.parameters.ProductUnit;
import com.opencsv.CSVReader;

import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Path;
import java.util.List;

public class OptimizedR24File implements OptimizedFile {

  private final Path path;

  public OptimizedR24File(final Path path) {
    this.path = path;
  }

  @Override
  public boolean contains(ProductUnit productUnit) throws IOException, InvalidUserInputException {
    try (CSVReader reader = new CSVReader(new FileReader(path.toFile()), ';', '"', 0)) {
      List<String[]> records = reader.readAll();
      for (String[] record : records) {
        if (record.length < 2) {
          throw new InvalidUserInputException(UserInputErrorEnum.INVALID_FILE);
        }
        if (record[0].equals(productUnit.getProductID()) && record[1].equals(productUnit.getUnitStr())) {
          return true;
        }
      }
    }

    return false;
  }
}
