/*
 * Copyright 2016 Red Hat, Inc. and/or its affiliates
 * and other contributors as indicated by the @author tags.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.keycloak.utils;

import java.util.Optional;
import java.util.Set;

import org.keycloak.Config;
import org.keycloak.Config.AbstractScope;
import org.keycloak.Config.Scope;
import org.keycloak.common.util.StringPropertyReplacer;
import org.keycloak.common.util.SystemEnvProperties;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.NullNode;

/**
 * @author <a href="mailto:sthorger@redhat.com">Stian Thorgersen</a>
 */
public class JsonConfigProvider implements Config.ConfigProvider {

    private JsonNode config;

    public JsonConfigProvider(JsonNode config) {
        this.config = config;
    }

    @Override
    public String getProvider(String spi) {
        JsonNode n = getNode(config, spi, "provider");
        return n != null ? replaceProperties(n.textValue()) : null;
    }

    @Override
    public String getDefaultProvider(String spi) {
        JsonNode n = getNode(config, spi, "provider-default");
        return n != null ? replaceProperties(n.textValue()) : null;
    }

    @Override
    public Config.Scope scope(String... path) {
        return new JsonScope(getNode(config, path));
    }

    private static JsonNode getNode(JsonNode root, String... path) {
        if (root == null) {
            return null;
        }
        JsonNode n = root;
        for (String p : path) {
            n = n.get(p);
            if (n == null) {
                return null;
            }
        }
        return n;
    }

    private String replaceProperties(String value) {
        return StringPropertyReplacer.replaceProperties(value, SystemEnvProperties.UNFILTERED::getProperty);
    }

    public class JsonScope extends AbstractScope {

        private JsonNode config;

        public JsonScope(JsonNode config) {
            this.config = config;
        }

        @Override
        public String get(String key) {
            return Optional.ofNullable(config).map(c -> c.get(key)).map(this::toString).orElse(null);
        }

        private String toString(JsonNode n) {
            String v = replaceProperties(n.textValue());
            return !StringUtil.isNullOrEmpty(v) ? v : null;
        }

        @Override
        public String[] getArray(String key) {
            if (config == null) {
                return null;
            }

            JsonNode n = config.get(key);
            if (n == null) {
                return null;
            } else if (n.isArray()) {
                String[] a = new String[n.size()];
                for (int i = 0; i < a.length; i++) {
                    a[i] = toString(n.get(i));
                }
                return a;
            } else {
               return new String[] { toString(n) };
            }
        }

        @Override
        public Config.Scope scope(String... path) {
            return new JsonScope(getNode(config, path));
        }

        @Override
        public Set<String> getPropertyNames() {
            throw new UnsupportedOperationException("Not implemented");
        }

        @Override
        public Scope root() {
            return new JsonScope(NullNode.getInstance());
        }

    }

}
