package de.ivu.elect.business.mandant.control;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MandantenResourceLoader {
  private static final Logger LOG = LoggerFactory.getLogger(MandantenResourceLoader.class);

  public static final List<String> MANDANTEN_RESOURCE_LINES;

  private static final Map<Long, Boolean> IS_IN_RESOUCRE = new ConcurrentHashMap<>();

  static {
    MANDANTEN_RESOURCE_LINES = load();
  }

  private static List<String> load() {
    try (InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("mandanten.txt")) {
      if (is != null) {
        try (BufferedReader buffer = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8))) {
          return buffer.lines().collect(Collectors.toList());
        }
      }
    } catch (Exception e) {
      LOG.warn("Mandanten nicht geladen: " + e.getMessage(), e);
    }
    return Collections.emptyList();
  }

  public static boolean isInMandantenResource(Long mandantenNummer) {
    if (mandantenNummer == null || MANDANTEN_RESOURCE_LINES.isEmpty()) {
      return false;
    }

    return IS_IN_RESOUCRE.computeIfAbsent(mandantenNummer, x -> MANDANTEN_RESOURCE_LINES.stream()
        .anyMatch(mandantenResourceLine -> mandantenResourceLine != null && mandantenResourceLine.startsWith(mandantenNummer + ";")));
  }

}
