/*
 * Copyright 2018 NAVER Corp.
 *
 * 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.navercorp.pinpoint.bootstrap;

import com.navercorp.pinpoint.bootstrap.agentdir.Assert;

import java.lang.reflect.Constructor;
import java.util.concurrent.Callable;


/**
 * @author emeroad
 */
public class AgentBootLoader {

    private static final SecurityManager SECURITY_MANAGER = System.getSecurityManager();

    private final ClassLoader classLoader;

    private final String bootClass;

    private final ContextClassLoaderExecuteTemplate<Object> executeTemplate;

    public AgentBootLoader(String bootClass, ClassLoader agentClassLoader) {
        this.bootClass = Assert.requireNonNull(bootClass, "bootClass");
        this.classLoader = Assert.requireNonNull(agentClassLoader, "agentClassLoader");
        this.executeTemplate = new ContextClassLoaderExecuteTemplate<Object>(agentClassLoader);
    }

    public Agent boot(final AgentOption agentOption) {

        final Class<?> bootStrapClazz = getBootStrapClass();

        final Object agent = executeTemplate.execute(new Callable<Object>() {
            @Override
            public Object call() throws Exception {
                try {
                    Constructor<?> constructor = bootStrapClazz.getDeclaredConstructor(AgentOption.class);
                    return constructor.newInstance(agentOption);
                } catch (InstantiationException e) {
                    throw new BootStrapException("boot create failed. Error:" + e.getMessage(), e);
                } catch (IllegalAccessException e) {
                    throw new BootStrapException("boot method invoke failed. Error:" + e.getMessage(), e);
                }
            }
        });

        if (agent instanceof Agent) {
            return (Agent) agent;
        } else {
            String agentClassName;
            if (agent == null) {
                agentClassName = "Agent is null";
            } else {
                agentClassName = agent.getClass().getName();
            }
            throw new BootStrapException("Invalid AgentType. boot failed. AgentClass:" + agentClassName);
        }
    }

    private Class<?> getBootStrapClass() {
        try {
            return this.classLoader.loadClass(bootClass);
        } catch (ClassNotFoundException e) {
            throw new BootStrapException("boot class not found. bootClass:" + bootClass + " Error:" + e.getMessage(), e);
        }
    }

}
