/*
 * 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 jetbrains.buildServer.parameters.ContextVariables;
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.Win32RegistryAccessor;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

/**
 * @author Yegor.Yarko
 *         Date: 18.09.2010
 */
public class WinRegistryScriptedPropertyProcessor extends EmptyScriptedPropertyProcessor {
    final Logger LOG = Logger.getInstance(WinRegistryScriptedPropertyProcessor.class.getName());
    private Win32RegistryAccessor myAccessor;

    WinRegistryScriptedPropertyProcessor(Win32RegistryAccessor win32RegistryAccessor) {
        super("winregistry");
        myAccessor = win32RegistryAccessor;
    }

    @Override
    public ProcessingResult process(@NotNull ParametersProvider parameters, @NotNull ContextVariables contextVariables) {
        throw new UnsupportedOperationException("Should provide registry key as parameter");
    }

    @Override
    public ProcessingResult process(@NotNull String value, @NotNull ParametersProvider parameters, @NotNull ContextVariables contextVariables) {
        final String registryValue = getRegistryValue(value);
        return new ProcessingResultImpl(registryValue == null ? "<not found>" : registryValue, true, true);
    }

//x32\HKEY_CURRENT_USER\Software\Ghisler\Total Commander\InstallDir
    @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.");
    }

}
