/*
 * 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 com.facebook.presto.server;

import com.facebook.airlift.log.Logger;
import com.facebook.airlift.node.NodeInfo;
import com.facebook.presto.Session;
import com.facebook.presto.spi.resourceGroups.ResourceGroupId;
import com.facebook.presto.spi.resourceGroups.SessionPropertyConfigurationManagerContext;
import com.facebook.presto.spi.session.SessionConfigurationContext;
import com.facebook.presto.spi.session.SessionPropertyConfigurationManager;
import com.facebook.presto.spi.session.SessionPropertyConfigurationManagerFactory;
import com.google.common.annotations.VisibleForTesting;

import javax.inject.Inject;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicReference;

import static com.facebook.presto.util.PropertiesUtil.loadProperties;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
import static java.lang.String.format;

public class SessionPropertyDefaults
{
    private static final Logger log = Logger.get(SessionPropertyDefaults.class);
    private static final File SESSION_PROPERTY_CONFIGURATION = new File("etc/session-property-config.properties");
    private static final String SESSION_PROPERTY_MANAGER_NAME = "session-property-config.configuration-manager";

    private final SessionPropertyConfigurationManagerContext configurationManagerContext;
    private final Map<String, SessionPropertyConfigurationManagerFactory> factories = new ConcurrentHashMap<>();
    private final AtomicReference<SessionPropertyConfigurationManager> delegate = new AtomicReference<>();

    @Inject
    public SessionPropertyDefaults(NodeInfo nodeInfo)
    {
        this.configurationManagerContext = new SessionPropertyConfigurationManagerContextInstance(nodeInfo.getEnvironment());
    }

    public void addConfigurationManagerFactory(SessionPropertyConfigurationManagerFactory sessionConfigFactory)
    {
        if (factories.putIfAbsent(sessionConfigFactory.getName(), sessionConfigFactory) != null) {
            throw new IllegalArgumentException(format("Session property configuration manager '%s' is already registered", sessionConfigFactory.getName()));
        }
    }

    public void loadConfigurationManager()
            throws IOException
    {
        if (!SESSION_PROPERTY_CONFIGURATION.exists()) {
            return;
        }

        Map<String, String> propertyMap = new HashMap<>(loadProperties(SESSION_PROPERTY_CONFIGURATION));

        log.info("-- Loading session property configuration manager --");

        String configManagerName = propertyMap.remove(SESSION_PROPERTY_MANAGER_NAME);
        checkArgument(configManagerName != null, "Session property configuration %s does not contain %s", SESSION_PROPERTY_CONFIGURATION, SESSION_PROPERTY_MANAGER_NAME);

        setConfigurationManager(configManagerName, propertyMap);

        log.info("-- Loaded session property configuration manager %s --", configManagerName);
    }

    @VisibleForTesting
    public void setConfigurationManager(String name, Map<String, String> properties)
    {
        SessionPropertyConfigurationManagerFactory factory = factories.get(name);
        checkState(factory != null, "Session property configuration manager '%s' is not registered", name);

        SessionPropertyConfigurationManager manager = factory.create(properties, configurationManagerContext);
        checkState(delegate.compareAndSet(null, manager), "sessionPropertyConfigurationManager is already set");
    }

    public Session newSessionWithDefaultProperties(Session session, Optional<String> queryType, ResourceGroupId resourceGroupId)
    {
        SessionPropertyConfigurationManager configurationManager = delegate.get();
        if (configurationManager == null) {
            return session;
        }

        SessionConfigurationContext context = new SessionConfigurationContext(
                session.getIdentity().getUser(),
                session.getSource(),
                session.getClientTags(),
                queryType,
                resourceGroupId);

        Map<String, String> systemPropertyOverrides = configurationManager.getSystemSessionProperties(context);
        Map<String, Map<String, String>> catalogPropertyOverrides = configurationManager.getCatalogSessionProperties(context);
        return session.withDefaultProperties(systemPropertyOverrides, catalogPropertyOverrides);
    }
}

@@ -1600,16 +1600,76 @@
 kState;%0A
+import static com.google.common.base.Strings.isNullOrEmpty;%0A
 import s
@@ -3162,29 +3162,14 @@
 pert
-yMap = new HashMap%3C%3E(
+ies = 
 load
@@ -3210,19 +3210,17 @@
 URATION)
-);%0A
+;
 %0A       
@@ -3224,128 +3224,51 @@
     
-log.info(%22-- Loading session property configuration manager --%22);%0A%0A        String configManagerName = propertyMap.remove
+checkArgument(!isNullOrEmpty(properties.get
 (SES
@@ -3294,17 +3294,18 @@
 ER_NAME)
-;
+),
 %0A       
@@ -3309,48 +3309,15 @@
     
-checkArgument(configManagerName != null,
+       
  %22Se
@@ -3369,16 +3369,32 @@
 ain %25s%22,
+%0A               
  SESSION
@@ -3417,16 +3417,32 @@
 URATION,
+%0A               
  SESSION
@@ -3475,19 +3475,20 @@
         
-set
+load
 Configur
@@ -3504,134 +3504,449 @@
 ger(
-configManagerName, propertyMap);%0A%0A        log.info(%22-- Loaded session property configuration manager %25s --%22, configManagerName
+properties);%0A    %7D%0A%0A    public void loadConfigurationManager(Map%3CString, String%3E properties)%0A    %7B%0A        properties = new HashMap%3C%3E(properties);%0A        String sessionPropertyManagerName = properties.remove(SESSION_PROPERTY_MANAGER_NAME);%0A        checkArgument(!isNullOrEmpty(sessionPropertyManagerName), %22%25s property must be present%22, SESSION_PROPERTY_MANAGER_NAME);%0A%0A        setConfigurationManager(sessionPropertyManagerName, properties
 );%0A 
@@ -4021,17 +4021,30 @@
 (String 
-n
+configManagerN
 ame, Map
@@ -4070,32 +4070,107 @@
 operties)%0A    %7B%0A
+        log.info(%22-- Loading session property configuration manager --%22);%0A%0A
         SessionP
@@ -4228,17 +4228,30 @@
 ies.get(
-n
+configManagerN
 ame);%0A  
@@ -4349,17 +4349,30 @@
 tered%22, 
-n
+configManagerN
 ame);%0A%0A 
@@ -4593,16 +4593,112 @@
 y set%22);
+%0A%0A        log.info(%22-- Loaded session property configuration manager %25s --%22, configManagerName);
 %0A    %7D%0A%0A

Refactor SessionPropertyDefaults to load properties map