/* Util_Lib - Copyright (c) 2010-2016 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.text.ParseException;
import net.mapeadores.util.primitives.FuzzyDate;


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

    private String version = "";
    private String repository = "";
    private FuzzyDate 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 = FuzzyDate.parse(value);
            } catch (ParseException 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 FuzzyDate date;

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

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

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

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


    }

}
