package com.bitnix.dirtcryptostore.util;

public final class SimpleJson {

    private SimpleJson() {
    }

    public static String findString(String json, String key) {
        String pattern = "\"" + key + "\":";
        int start = json.indexOf(pattern);
        if (start == -1) {
            return null;
        }

        int firstQuote = json.indexOf('"', start + pattern.length());
        if (firstQuote == -1) {
            return null;
        }

        int secondQuote = json.indexOf('"', firstQuote + 1);
        if (secondQuote == -1) {
            return null;
        }

        return json.substring(firstQuote + 1, secondQuote);
    }

    public static Integer findInt(String json, String key) {
        String pattern = "\"" + key + "\":";
        int start = json.indexOf(pattern);
        if (start == -1) {
            return null;
        }

        int index = start + pattern.length();
        while (index < json.length() && Character.isWhitespace(json.charAt(index))) {
            index++;
        }

        int end = index;
        while (end < json.length() && (Character.isDigit(json.charAt(end)) || json.charAt(end) == '-')) {
            end++;
        }

        if (end == index) {
            return null;
        }

        try {
            return Integer.parseInt(json.substring(index, end));
        } catch (NumberFormatException ignored) {
            return null;
        }
    }

    public static Long findLong(String json, String key) {
        String pattern = "\"" + key + "\":";
        int start = json.indexOf(pattern);
        if (start == -1) {
            return null;
        }

        int index = start + pattern.length();
        while (index < json.length() && Character.isWhitespace(json.charAt(index))) {
            index++;
        }

        int end = index;
        while (end < json.length() && (Character.isDigit(json.charAt(end)) || json.charAt(end) == '-')) {
            end++;
        }

        if (end == index) {
            return null;
        }

        try {
            return Long.parseLong(json.substring(index, end));
        } catch (NumberFormatException ignored) {
            return null;
        }
    }
}
