/* Util_Lib - Copyright (c) 2010-2025 Vincent Calame - Exemole
 * Logiciel libre donné sous triple licence :
 * 1) selon les termes de la CeCILL V2
 * 2) selon les termes de l’EUPL V.1.1
 * 3) selon les termes de la GNU GPLv3
 * Voir le fichier licences.txt
 */


package net.mapeadores.util.buildinfo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.time.LocalDate;
import java.time.format.DateTimeParseException;


/**
 *
 * @author Vincent Calame
 */
public class BuildInfoParser {

    private String version = "";
    private String repository = "";
    private LocalDate date = null;

    private BuildInfoParser() {

    }

    public static BuildInfo parse(InputStream inputStream) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
        BuildInfoParser parser = new BuildInfoParser();
        String ligne;
        while ((ligne = reader.readLine()) != null) {
            parser.parse(ligne);
        }
        return parser.toBuildInfo();
    }

    private void parse(String s) {
        int idx = s.indexOf(':');
        if (idx == -1) {
            return;
        }
        String key = s.substring(0, idx).trim();
        if (key.length() == 0) {
            return;
        }
        key = key.toLowerCase();
        String value = s.substring(idx + 1).trim();
        if (value.length() == 0) {
            return;
        }
        if (key.equals("version")) {
            version = value;
        } else if (key.equals("repository")) {
            repository = value;
        } else if (key.equals("svn-revision")) {
            repository = "SVN Revision #" + value;
        } else if (key.equals("date")) {
            try {
                date = LocalDate.parse(value);
            } catch (DateTimeParseException pe) {
            }
        }
    }

    private BuildInfo toBuildInfo() {
        return new InternalBuildInfo(version, repository, date);
    }


    private static class InternalBuildInfo implements BuildInfo {

        private final String version;
        private final String repository;
        private final LocalDate date;

        private InternalBuildInfo(String version, String repository, LocalDate date) {
            this.version = version;
            this.repository = repository;
            this.date = date;
        }

        @Override
        public String getVersion() {
            return version;
        }

        @Override
        public String getRepository() {
            return repository;
        }

        @Override
        public LocalDate getDate() {
            return date;
        }


    }

}
