package org.bdware.sc;

import com.android.dx.cf.direct.DirectClassFile;
import com.android.dx.cf.direct.StdAttributeFactory;
import com.android.dx.command.dexer.DxContext;
import com.android.dx.dex.DexOptions;
import com.android.dx.dex.cf.CfOptions;
import com.android.dx.dex.cf.CfTranslator;
import com.android.dx.dex.file.ClassDefItem;
import com.android.dx.dex.file.DexFile;

import java.util.Map;

public class DX {
    public static byte[] clzsToDex(Map<String, byte[]> clzs) {
        try {
            DxContext context = new DxContext();
            DexOptions dexOptions = new DexOptions();
            dexOptions.minSdkVersion = 26;
            CfOptions cfOptions = new CfOptions();
            DexFile outputDex = new DexFile(dexOptions);
            for (String str : clzs.keySet()) {
                DirectClassFile dcf =
                        new DirectClassFile(
                                clzs.get(str),
                                toInternalName(str) + ".class",
                                cfOptions.strictNameCheck);
                dcf.setAttributeFactory(StdAttributeFactory.THE_ONE);
                ClassDefItem item =
                        CfTranslator.translate(
                                context, dcf, clzs.get(str), cfOptions, dexOptions, outputDex);
                outputDex.add(item);
            }
            return outputDex.toDex(null, false);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String toInternalName(String plain) {
        return plain.replaceAll("\\.", "/");
    }
}
