package cz.senslog.connector.push.rest.senslog.v1;

import cz.senslog.connector.model.config.DefaultConfig;
import cz.senslog.connector.model.config.HostConfig;
import cz.senslog.connector.model.config.PropertyConfig;

import java.net.URI;
import java.net.URISyntaxException;

import static cz.senslog.connector.tools.json.BasicJson.objectToJson;

/**
 * The class {@code SenslogV1Config} represents a configuration class for the {@link SenslogV1Pusher}.
 *
 * @author Lukas Cerny
 * @version 1.0
 * @since 1.0
 */
public class SenslogV1Config {

    public static class AuthConfig {

        private final String username;
        private final String password;

        private AuthConfig(PropertyConfig config) {
            this.username = config.getStringProperty("username");
            this.password = config.getStringProperty("password");
        }

        public String getUsername() {
            return username;
        }

        public String getPassword() {
            return password;
        }
    }

    private final String baseUrl;
    private final URI baseUri;
    private final AuthConfig auth;

    /**
     * Constructor sets class attributes from default input configuration class {@link DefaultConfig}.
     * From the default configuration are dynamically get properties for attributes.
     * @param config - default configuration
     */
    public SenslogV1Config(DefaultConfig config) {
        this.baseUrl = config.getStringProperty("baseUrl");
        this.auth = config.containsProperty("auth") ? new AuthConfig(config.getPropertyConfig("auth")) : null;

        try {
            this.baseUri = new URI(baseUrl);
        } catch (URISyntaxException e) {
            throw new RuntimeException("The config is in invalid format. " + e.getMessage());
        }
    }

    public String getBaseUrl() {
        return baseUrl;
    }

    public AuthConfig getAuth() {
        return auth;
    }

    public URI getBaseURI() {
        return baseUri;
    }

    @Override
    public String toString() {
        return objectToJson(this);
    }
}
