package com.secureline.server;

import android.content.Context;
import android.provider.Settings;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;

final class SecureLineNotificationWipeStore {

    private static final String KEY_ENABLED =
            "secureline_message_wipe_enabled";

    private static final String KEY_SECRET_HASH =
            "secureline_message_wipe_secret_hash";

    private SecureLineNotificationWipeStore() {}

    static boolean isEnabled(Context context) {
        return Settings.Global.getInt(
                context.getContentResolver(),
                KEY_ENABLED,
                0
        ) == 1;
    }

    static void setEnabled(Context context, boolean enabled) {
        Settings.Global.putInt(
                context.getContentResolver(),
                KEY_ENABLED,
                enabled ? 1 : 0
        );
    }

    static void setSecret(Context context, String secret) {
        validateSecret(secret);

        Settings.Global.putString(
                context.getContentResolver(),
                KEY_SECRET_HASH,
                sha256(secret.trim())
        );
    }

    static String getSecretHash(Context context) {
        return Settings.Global.getString(
                context.getContentResolver(),
                KEY_SECRET_HASH
        );
    }

    static void validateSecret(String secret) {
        if (secret == null || secret.trim().length() < 12) {
            throw new IllegalArgumentException(
                    "Message wipe secret must be at least 12 characters"
            );
        }

        if (secret.trim().matches(".*\\s+.*")) {
            throw new IllegalArgumentException(
                    "Message wipe secret must not contain spaces"
            );
        }
    }

    static String sha256(String value) {
        try {
            MessageDigest md =
                    MessageDigest.getInstance("SHA-256");

            byte[] digest =
                    md.digest(value.getBytes(StandardCharsets.UTF_8));

            StringBuilder sb =
                    new StringBuilder();

            for (byte b : digest) {
                sb.append(String.format("%02x", b));
            }

            return sb.toString();

        } catch (Exception e) {
            throw new IllegalStateException(e);
        }
    }
}
