/*
 * Copyright 2023 the original author or authors.
 *
 * 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.gradle.internal.classpath.types;

import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import org.apache.commons.io.IOUtils;
import org.gradle.internal.hash.HashCode;
import org.gradle.internal.lazy.Lazy;

import java.io.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;
import java.util.Collections;
import java.util.Map;
import java.util.Optional;
import java.util.Properties;
import java.util.Set;

/**
 * Provides instrumented super types for a given type for core Gradle types.
 *
 * Note: It returns only instrumented types that are instrumented with {@link org.gradle.internal.instrumentation.api.annotations.InterceptInherited}.
 */
public class GradleCoreInstrumentingTypeRegistry implements InstrumentingTypeRegistry {

    /**
     * Generated by gradlebuild.distributions plugin
     */
    private static final String RESOURCE_FILE = "/instrumented-super-types.properties";
    private static final String HASH_FILE = "/instrumented-super-types-hash.txt";

    private static final Lazy<Map<String, Set<String>>> INSTRUMENTED_SUPER_TYPES = Lazy.locking().of(GradleCoreInstrumentingTypeRegistry::loadInstrumentedSuperTypes);
    private static final Lazy<Optional<HashCode>> INSTRUMENTED_HASH_CODE = Lazy.locking().of(GradleCoreInstrumentingTypeRegistry::loadInstrumentedSuperTypesHash);

    @Override
    public Set<String> getSuperTypes(String type) {
        return INSTRUMENTED_SUPER_TYPES.get().getOrDefault(type, Collections.emptySet());
    }

    @Override
    public boolean isEmpty() {
        return INSTRUMENTED_SUPER_TYPES.get().isEmpty();
    }

    public Optional<HashCode> getInstrumentedFileHash() {
        return INSTRUMENTED_HASH_CODE.get();
    }

    private static Map<String, Set<String>> loadInstrumentedSuperTypes() {
        try (InputStream stream = GradleCoreInstrumentingTypeRegistry.class.getResourceAsStream(RESOURCE_FILE)) {
            Properties properties = new Properties();
            properties.load(stream);
            ImmutableMap.Builder<String, Set<String>> builder = ImmutableMap.builder();
            properties.forEach((k, v) -> builder.put((String) k, ImmutableSet.copyOf(v.toString().split(","))));
            return builder.build();
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    }

    private static Optional<HashCode> loadInstrumentedSuperTypesHash() {
        try (InputStream stream = GradleCoreInstrumentingTypeRegistry.class.getResourceAsStream(HASH_FILE)) {
            byte[] bytes = IOUtils.toByteArray(stream);
            if (bytes.length == 0) {
                return Optional.empty();
            }
            return Optional.of(HashCode.fromBytes(bytes));
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    }
}
