package de.ivu.elect.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Nullable;

public class ThirdPartyReader {

  private static final Pattern PATERN = Pattern.compile("\\((.+)\\)\\s+(.+)\\s+\\((.+)\\s+-\\s+(.+)\\)");

  public List<ThirdPartyInfo> readThirdPartyInfos() {
    try (InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("THIRD-PARTY.txt")) {
      if (is != null) {
        return readThirdPartyInfos(is);
      }
    } catch (IOException e) {
      // ignore
    }
    return Collections.emptyList();
  }

  public List<ThirdPartyInfo> readThirdPartyInfos(InputStream inputStream) throws IOException {
    List<ThirdPartyInfo> result = new ArrayList<>();
    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
    while (reader.ready()) {
      String line = reader.readLine();
      ThirdPartyInfo thirdPartyInfo = parse(line);
      if (thirdPartyInfo != null) {
        result.add(thirdPartyInfo);
      }
    }
    return result;

  }

  @Nullable
  protected ThirdPartyInfo parse(String line) {

    Matcher matcher = PATERN.matcher(line);
    if (matcher.find()) {
      return new ThirdPartyInfo(matcher.group(2), matcher.group(3), matcher.group(1), matcher.group(4));
    }
    return null;
  }


}


