/*
 * Copyright 2018 Scytl Secure Electronic Voting SA
 *
 * All rights reserved
 *
 * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
 */
package com.scytl.products.ov.channel.cc.orchestrator.commons.config;

import static java.text.MessageFormat.format;

import java.io.StringReader;
import java.lang.IllegalStateException;

import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonReader;

import com.scytl.products.ov.commons.messaging.Topic;

/**
 * Utility class which holds information about the topics used by the
 * application.
 */
public final class TopicsConfig {
    /**
     * Topic used for the results ready notification.
     */
    public static final Topic HA_TOPIC;

    private static final String CC_TOPIC_NAMES_PROPERTY = "cc_topic_names";

    static {
        String json = System.getProperty(CC_TOPIC_NAMES_PROPERTY);
        if (json == null) {
            throw new IllegalStateException(
                format("System property ''{0}'' is missing.",
                    CC_TOPIC_NAMES_PROPERTY));
        }

        Parser parser = new Parser();
        parser.parse(json);

        HA_TOPIC = parser.ha;
    }

    private TopicsConfig() {
    }

    /**
     * Topic names parser. For internal use only.
     */
    static class Parser {
        private static final String HA = "or-ha";

        /**
         * Topic used for the results ready notification. For internal use only
         */
        Topic ha;

        /**
         * Parses a given JSON and populates the topic names. For internal use
         * only.
         * 
         * @param json
         *            the json.
         */
        void parse(String json) {
            JsonObject object;
            try (JsonReader reader =
                Json.createReader(new StringReader(json))) {
                object = reader.readObject();
            }
            ha = new Topic(object.getString(HA));
        }
    }
}
