import subprocess
from .util import *

import re

# Task dependencies
from .patch_smali import patch_smali

def to_dex_name(smali_name: str):
    if smali_name == 'smali':
        return 'classes.dex'
    else:
        num = re.match(r"smali_classes([0-9]+)", smali_name).group(1)
        return f"classes{num}.dex"

def compile_smali():
    _ = patch_smali()
    
    COMPILED_SMALI_DIR.mkdir(parents=True, exist_ok=True)
    
    print("Compiling smali...")
    for smali_dir in PATCHED_SMALI_DIR.glob("*"):
        dest_dex = COMPILED_SMALI_DIR / to_dex_name(smali_dir.name)

        # Don't compile if not necessary
        # This depends on merge_into touching directories with copying
        if dest_dex.exists() and smali_dir.stat().st_mtime < dest_dex.stat().st_mtime:
            print(F"Skipping {dest_dex.name}")
            continue
        
        print(f"Compiling {smali_dir.name} => {dest_dex.name}...")        
        _ = subprocess.run([JAVA_BIN, "-jar", SMALI_COMPILER, "a", "-a", "26", smali_dir, "-o", dest_dex])