package com.axis.innovators.box.decompilation.gui;

import org.benf.cfr.reader.api.ClassFileSource;
import org.benf.cfr.reader.bytecode.analysis.parse.utils.Pair;

import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;
import java.util.Collections;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

public class JarClassFileSource implements ClassFileSource {
    private final JarFile jarFile;

    public JarClassFileSource(JarFile jarFile) {
        this.jarFile = jarFile;
    }

    @Override
    public void informAnalysisRelativePathDetail(String usePath, String classFilePath) {
    }

    @Override
    public Collection<String> addJar(String jarPath) {
        return Collections.emptyList();
    }

    @Override
    public String getPossiblyRenamedPath(String path) {
        return path;
    }

    @Override
    public Pair<byte[], String> getClassFileContent(String path) throws IOException {
        JarEntry entry = jarFile.getJarEntry(path);
        if (entry == null) {
            return null;
        }

        try (InputStream is = jarFile.getInputStream(entry)) {
            byte[] bytes = new byte[(int) entry.getSize()];
            is.read(bytes);
            return Pair.make(bytes, path);
        }
    }
}
