/*-
 * ~~~~~~licensing~~~~~~
 * core-support-design
 * ==========
 * Copyright (C) 2020 - 2025 EmDev LLC
 * ==========
 * You may not use this file except in accordance with the License Terms of the Copyright
 * Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property
 * rights to the Software and any copies are the property of the Copyright Holder. Unless
 * it is explicitly allowed the Copyright Holder, the User is prohibited from using the
 * Software for commercial purposes to provide services to third parties.
 * 
 * The Copyright Holder hereby declares that the Software is provided on an "AS IS".
 * Under no circumstances does the Copyright Holder guarantee or promise that the
 * Software provided by him will be suitable or not suitable for the specific purposes
 * of the User, that the Software will meet all commercial and personal subjective
 * expectations of the User, that the Software will work properly, without technical
 * errors, quickly and uninterruptedly.
 * 
 * Under no circumstances shall the Copyright Holder or its Affiliates is not liable
 * to the User for any direct or indirect losses of the User, his expenses or actual
 * damage, including, downtime; loss of bussines; lost profit; lost earnings; loss
 * or damage to data, property, etc.
 * ~~~~~~/licensing~~~~~~
 */
package ru.entaxy.platform.core.support.design.openapi.utils;

import com.google.common.base.Joiner;
import org.eclipse.jdt.core.compiler.IProblem;
import org.eclipse.jdt.internal.compiler.ClassFile;
import org.eclipse.jdt.internal.compiler.CompilationResult;
import org.eclipse.jdt.internal.compiler.ICompilerRequestor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CompilerRequestor implements ICompilerRequestor {
    private static final Logger log = LoggerFactory.getLogger(CompilerRequestor.class);

    private final Map<String, List<String>> problemList = new HashMap<>();

    private final String outputDir;

    public CompilerRequestor(String outputDir) {
        this.outputDir = outputDir;
    }

    @Override
    public void acceptResult(CompilationResult result) {
        if (result.hasProblems()) {
            IProblem[] problems = result.getProblems();
            for (IProblem problem : problems) {
                if (problem.isError()) {
                    String fileName =
                            new String(problem.getOriginatingFileName());
                    List<String> errors = problemList.getOrDefault(fileName, new ArrayList<>());
                    errors.add(String.format("%s %d: %s", fileName, problem.getSourceLineNumber(), problem.getMessage()));
                    problemList.put(fileName, errors);
                }
            }
        }
        if (problemList.isEmpty()) {
            createOutDirIfNotExist(this.outputDir);
            ClassFile[] classFiles = result.getClassFiles();
            for (ClassFile classFile : classFiles) {
                char[][] compoundName =
                        classFile.getCompoundName();
                StringBuilder classFileName = new StringBuilder(outputDir).append('/');
                for (int j = 0; j < compoundName.length; j++) {
                    if (j > 0) {
                        classFileName.append('/');
                    }
                    classFileName.append(compoundName[j]);
                    if (j == compoundName.length - 2) {
                        createOutDirIfNotExist(classFileName.toString());
                    }
                }

                byte[] bytes = classFile.getBytes();
                classFileName.append(".class");
                try (FileOutputStream classStream = new FileOutputStream(classFileName.toString());
                     BufferedOutputStream bos = new BufferedOutputStream(classStream)) {
                    bos.write(bytes);
                } catch (IOException e) {
                    log.error("Error writing classfile {}", classFileName, e);
                }
            }
        } else {
            problemList.forEach((file, errors) -> log.error("Error compiling {}:\n {}", file, Joiner.on("\n\t").join(errors)));
        }
    }

    private void createOutDirIfNotExist(String directory) {
        File f = new File(directory);
        if (! f.exists()) {
            if (! f.mkdirs()) {
                throw new RuntimeException("Cannot create output directory " + directory);
            }
        } else if (! f.isDirectory()) {
            throw new RuntimeException("File " + directory + " is not directory");
        }
    }

    public Map<String, List<String>> getProblemList() {
        return problemList;
    }
}
