/*
 * Copyright 2000-2010 JetBrains s.r.o.
 *
 * 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 jetbrains.buildServer.scriptedProperties;

import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.SystemInfo;
import jetbrains.buildServer.parameters.ParameterResolver;
import jetbrains.buildServer.parameters.ParametersProvider;
import jetbrains.buildServer.parameters.ProcessingResult;
import jetbrains.buildServer.parameters.impl.ProcessingResultImpl;
import jetbrains.buildServer.util.Bitness;
import jetbrains.buildServer.util.StringUtil;
import jetbrains.buildServer.util.Win32RegistryAccessor;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

/**
 * @author jetbrains
 *         Date: Sep 4, 2010
 */
public class RegistryValueParameterResolver implements ParameterResolver {
    final Logger LOG = Logger.getInstance(RegistryValueParameterResolver.class.getName());
    public static final String TEAMCITY_REGISTRY_PREFIX = "##winregistry::";

    private Win32RegistryAccessor myAccessor;
    private boolean active;

    public RegistryValueParameterResolver(Win32RegistryAccessor win32RegistryAccessor) {
        myAccessor = win32RegistryAccessor;
        active = SystemInfo.isWindows;
    }

    @NotNull
    public ProcessingResult resolve(@NotNull String key, @NotNull String value, @NotNull ParametersProvider parameters) {
        if (!active){
            return new ProcessingResultImpl(value, false, true);
        }
        //todo: parse it
        if (value.startsWith(TEAMCITY_REGISTRY_PREFIX)) {
            String registryKey = value.substring(TEAMCITY_REGISTRY_PREFIX.length(), value.length());
            if (StringUtil.isEmpty(registryKey)) {
                return new ProcessingResultImpl(TEAMCITY_REGISTRY_PREFIX + "Error: empty Registry key specified", true, true);
            }
            try {
                final String registryValue = getRegistryValue(registryKey);
                if (registryValue == null) {
                    LOG.debug("Did not find registry key '" + registryKey + "'.");
                    return new ProcessingResultImpl("<not found>", true, true);
                }
                return new ProcessingResultImpl(registryValue, true, true);
            } catch (Exception e) {
                LOG.debug("Error retrieving registry key.", e);
                return new ProcessingResultImpl(TEAMCITY_REGISTRY_PREFIX + "Error: " + e.getMessage(), true, true);
            }
        } else {
            return new ProcessingResultImpl(value, false, true);
        }
    }

    @Nullable
    private String getRegistryValue(@NotNull final String fullKey) {
        //todo: due error reporting
        final String normalizedKey = fullKey.replace("/", "\\");
        String registryKey = normalizedKey;
        Bitness bitsSelector = Bitness.BIT32;
        if (normalizedKey.startsWith("x64\\")) {
            bitsSelector = Bitness.BIT64;
            registryKey = normalizedKey.substring("x64\\".length());
        } else if (normalizedKey.startsWith("x32\\")) {
            bitsSelector = Bitness.BIT32;
            registryKey = normalizedKey.substring("x32\\".length());
        }
        final int hiveEndIndex = registryKey.indexOf("\\");
        final int leafNameStartIndex = registryKey.lastIndexOf("\\");
        final String hiveName = registryKey.substring(0, hiveEndIndex);
        final String keyCentralPart = registryKey.substring(hiveEndIndex + 1, leafNameStartIndex);
        final String leafName = registryKey.substring(leafNameStartIndex + 1);

        final String value = myAccessor.readRegistryText(getRootKey(hiveName), bitsSelector, keyCentralPart, leafName);
        LOG.debug("Retrieved registry key '" + fullKey + "'. Value: " + value);
        return value;
    }

    @NotNull
    private Win32RegistryAccessor.Hive getRootKey(String rootKey) {
        if ("HKEY_CURRENT_USER".equals(rootKey)) {
            return Win32RegistryAccessor.Hive.CURRENT_USER;
        }
        if ("HKEY_CLASSES_ROOT".equals(rootKey)) {
            return Win32RegistryAccessor.Hive.CLASSES_ROOT;
        }
        if ("HKEY_LOCAL_MACHINE".equals(rootKey)) {
            return Win32RegistryAccessor.Hive.LOCAL_MACHINE;
        }
        throw new IllegalArgumentException("Cannot parse '" + rootKey + "' into registry hive.");
    }
}
