/*
 * Copyright 2021 Red Hat, Inc. and/or its affiliates.
 *
 * 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.kie.kogito.codegen.openapi.client.di;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Optional;

import org.kie.kogito.codegen.api.context.KogitoBuildContext;
import org.kie.kogito.codegen.openapi.client.OpenApiClientException;
import org.kie.kogito.codegen.openapi.client.OpenApiSpecDescriptor;

import com.github.javaparser.StaticJavaParser;
import com.github.javaparser.ast.CompilationUnit;
import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration;

/**
 * Configure dependency injection for generated OpenApi Client files
 */
public class DependencyInjectionConfigurer {

    private final ServicesConfigurationHandler servicesConfigurationHandler;
    private final ApplicationPropertiesHandler applicationPropertiesHandler;

    public DependencyInjectionConfigurer(final KogitoBuildContext context) {
        this.servicesConfigurationHandler = new ServicesConfigurationHandler(context);
        this.applicationPropertiesHandler = new ApplicationPropertiesHandler(context);
    }

    /**
     * Parse the given generated file and apply all dependency injection configuration required by a Kogito Application.
     *
     * @param originalGeneratedFile the file as generated by the OpenApi Generator tool
     * @param descriptor the information about the OpenApi Specification
     * @return the parsed file with dependency injection configured if it has an interface or class defined
     */
    public CompilationUnit parseAndConfigure(final File originalGeneratedFile, final OpenApiSpecDescriptor descriptor) {
        try {
            final CompilationUnit compilationUnit = StaticJavaParser.parse(originalGeneratedFile);
            final Optional<ClassOrInterfaceDeclaration> clazz = compilationUnit.findFirst(ClassOrInterfaceDeclaration.class);
            if (clazz.isPresent()) {
                this.servicesConfigurationHandler.handle(clazz.get(), descriptor, originalGeneratedFile);
                this.applicationPropertiesHandler.handle(clazz.get(), descriptor, originalGeneratedFile);
            }
            return compilationUnit;
        } catch (FileNotFoundException e) {
            throw new OpenApiClientException("Failed to add process dependency injection configuration to OpenApi generated file: " + originalGeneratedFile, e);
        }
    }
}
