import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Map;
import com.alibaba.fastjson.JSON;

public class PubgHdJsonPathHelper {
    private static final String BASE_ANDROID_PATH = "/Android/data/com.tencent.tmgp.pubgmhd/files/UE4Game/ShadowTrackerExtra/ShadowTrackerExtra/Saved/json/";

    public static String checkAndCreateJsonDir(boolean isExternalStorage) throws IOException {
        String fullJsonDir = isExternalStorage 
                ? android.os.Environment.getExternalStorageDirectory().getAbsolutePath() + BASE_ANDROID_PATH 
                : BASE_ANDROID_PATH;

        Path jsonDirPath = Paths.get(fullJsonDir);
        if (!Files.exists(jsonDirPath)) {
            Files.createDirectories(jsonDirPath);
        }
        return fullJsonDir;
    }

    public static Map<String, Object> readJsonFile(String jsonFileName, boolean isExternalStorage) throws IOException {
        String jsonDir = checkAndCreateJsonDir(isExternalStorage);
        Path jsonFilePath = Paths.get(jsonDir, jsonFileName);

        if (!Files.exists(jsonFilePath)) {
            throw new FileNotFoundException();
        }

        String jsonContent = new String(Files.readAllBytes(jsonFilePath), StandardCharsets.UTF_8);
        return JSON.parseObject(jsonContent, Map.class);
    }

    public static void writeJsonFile(String jsonFileName, Map<String, Object> jsonData, boolean isExternalStorage) throws IOException {
        String jsonDir = checkAndCreateJsonDir(isExternalStorage);
        Path jsonFilePath = Paths.get(jsonDir, jsonFileName);

        String jsonContent = JSON.toJSONString(jsonData, true);
        Files.write(jsonFilePath, jsonContent.getBytes(StandardCharsets.UTF_8));
    }

    public static boolean deleteJsonFile(String jsonFileName, boolean isExternalStorage) throws IOException {
        String jsonDir = checkAndCreateJsonDir(isExternalStorage);
        Path jsonFilePath = Paths.get(jsonDir, jsonFileName);

        if (Files.exists(jsonFilePath)) {
            Files.delete(jsonFilePath);
            return true;
        }
        return false;
    }

    public static void main(String[] args) {
        try {
            String testJson = "test_config.json";
            Map<String, Object> data = readJsonFile(testJson, true);
            writeJsonFile(testJson, data, true);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}