package de.ivu.elect.util;

import java.io.IOException;
import java.net.URL;
import java.time.Instant;
import java.util.Date;
import java.util.Enumeration;
import java.util.jar.Attributes;
import java.util.jar.JarFile;
import java.util.jar.Manifest;

/**
 *  on 09.06.2017.
 */
public class ManifestVersionParser {

  private final Class<?> clazz;

  private final String groupId;

  private final String artifactId;

  String version = null;

  Date timestamp = null;

  public ManifestVersionParser(Class<?> clazz, String groupId, String artifactId) {
    this.clazz = clazz;
    this.groupId = groupId;
    this.artifactId = artifactId;
  }

  public String getVersion() {
    if (version == null) {
      parse();
    }
    return version;

  }

  public Date getTimestamp() {
    if (version == null) {
      parse();
    }
    return timestamp;
  }

  protected void parse() {

    try {
      Enumeration<URL> resources = clazz.getClassLoader().getResources(JarFile.MANIFEST_NAME);
      while (resources.hasMoreElements()) {
        try {
          Manifest manifest = new Manifest(resources.nextElement().openStream());
          Attributes mainAttribs = manifest.getMainAttributes();
          String groupIdValue = mainAttribs.getValue("groupId");
          if (this.groupId.equals(groupIdValue)) {
            String artifactIdValue = mainAttribs.getValue("artifactId");
            if (this.artifactId.equals(artifactIdValue)) {
              version = mainAttribs.getValue("version");
              try {
                String timestampValue = mainAttribs.getValue("timestamp");
                this.timestamp = Date.from(Instant.parse(timestampValue));
              } catch (Exception e) {
                // ignore
              }
              break;
            }
          }

        } catch (IOException e) {
          // handle
        }
      }
    } catch (Exception e) {
      // ignore
      version = "-";
      timestamp = null;
    }

  }

}
