/*
 * Copyright 2016 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.initialization;

import org.gradle.api.GradleException;
import org.gradle.internal.classloader.ClassLoaderUtils;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Opcodes;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.LinkedHashSet;
import java.util.Set;

import static java.nio.charset.StandardCharsets.UTF_8;
import static org.gradle.internal.classpath.types.CommonTypes.OBJECT_TYPE;


/**
 * Enriches class loading with empty interfaces for certain types that have been removed,
 * but which are baked into the bytecode generated by the Groovy compiler.
 */
public class DefaultLegacyTypesSupport implements LegacyTypesSupport {
    private static final int JAVA_BYTE_CODE_COMPATIBILITY = Opcodes.V1_8;
    private static final int INTERFACE_ACCESS_MODIFIERS = Opcodes.ACC_PUBLIC | Opcodes.ACC_SYNTHETIC | Opcodes.ACC_INTERFACE | Opcodes.ACC_ABSTRACT;

    private final ConventionInterfaceGenerator conventionGenerator = new ConventionInterfaceGenerator();
    private final Set<String> classesToMixInGroovyObject = readClassNames("converted-types.txt");
    private final Set<String> syntheticClasses = getRemovedClassNames();

    private Set<String> getRemovedClassNames() {
        Set<String> removedClassNames = readClassNames("removed-types.txt");
        removedClassNames.addAll(conventionGenerator.getRemovedClassNames());
        return removedClassNames;
    }

    @Override
    public Set<String> getClassesToMixInGroovyObject() {
        return classesToMixInGroovyObject;
    }

    @Override
    public Set<String> getSyntheticClasses() {
        return syntheticClasses;
    }

    private Set<String> readClassNames(String resourceName) {
        Set<String> classNames = new LinkedHashSet<>();
        URL resource = LegacyTypesSupport.class.getResource(resourceName);
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(resource.openStream(), UTF_8))) {
            String line;
            while ((line = reader.readLine()) != null) {
                classNames.add(line.trim());
            }
        } catch (IOException e) {
            throw new GradleException("Could not load class names from '" + resource + "'.", e);
        }
        return classNames;
    }

    @Override
    public byte[] generateSyntheticClass(String name) {
        if (conventionGenerator.isConventionClass(name)) {
            return conventionGenerator.generateConventionClass(name);
        }
        return generateEmptyInterface(name);
    }

    private static byte[] generateEmptyInterface(String name) {
        ClassWriter visitor = new ClassWriter(0);
        visitor.visit(JAVA_BYTE_CODE_COMPATIBILITY, INTERFACE_ACCESS_MODIFIERS, getInternalName(name), null, OBJECT_TYPE.getInternalName(), null);
        visitor.visitEnd();
        return visitor.toByteArray();
    }

    private static String getInternalName(String className) {
        return className.replace('.', '/');
    }

    /**
     * Injects the interfaces into an arbitrary classloader via
     * {@link ClassLoader#defineClass(String, byte[], int, int)}.
     */
    @Override
    public void injectEmptyInterfacesIntoClassLoader(ClassLoader classLoader) {
        try {
            for (String name : syntheticClasses) {
                byte[] bytes = generateSyntheticClass(name);
                ClassLoaderUtils.define(classLoader, name, bytes);
            }
        } catch (Exception e) {
            throw new GradleException("Could not inject synthetic classes.", e);
        }
    }
}
