package club.clubk.ktag.apps.mqttbroker;

import android.content.Context;
import android.util.Log;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.LinkedHashMap;
import java.util.Map;

public class CredentialManager {
    private static final String TAG = "CredentialManager";
    private static final String CREDENTIALS_FILE = "mqtt_credentials.txt";

    public static Map<String, String> loadCredentials(Context context) {
        Map<String, String> credentials = new LinkedHashMap<>();
        File file = new File(context.getFilesDir(), CREDENTIALS_FILE);
        if (!file.exists()) {
            return credentials;
        }
        try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
            String line;
            while ((line = reader.readLine()) != null) {
                line = line.trim();
                if (line.isEmpty()) continue;
                int sep = line.indexOf(':');
                if (sep > 0 && sep < line.length() - 1) {
                    String username = line.substring(0, sep);
                    String hash = line.substring(sep + 1);
                    credentials.put(username, hash);
                }
            }
        } catch (IOException e) {
            Log.e(TAG, "Error loading credentials", e);
        }
        return credentials;
    }

    public static void saveCredentials(Context context, Map<String, String> credentials) {
        File file = new File(context.getFilesDir(), CREDENTIALS_FILE);
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
            for (Map.Entry<String, String> entry : credentials.entrySet()) {
                writer.write(entry.getKey() + ":" + entry.getValue());
                writer.newLine();
            }
        } catch (IOException e) {
            Log.e(TAG, "Error saving credentials", e);
        }
    }

    public static void addCredential(Context context, String username, String password) {
        Map<String, String> credentials = loadCredentials(context);
        credentials.put(username, hashPassword(password));
        saveCredentials(context, credentials);
    }

    public static void removeCredential(Context context, String username) {
        Map<String, String> credentials = loadCredentials(context);
        credentials.remove(username);
        saveCredentials(context, credentials);
    }

    public static int getCredentialCount(Context context) {
        return loadCredentials(context).size();
    }

    public static boolean checkCredential(String username, byte[] password, Map<String, String> credentials) {
        if (username == null || password == null || credentials == null) {
            return false;
        }
        String storedHash = credentials.get(username);
        if (storedHash == null) {
            return false;
        }
        String providedHash = hashPassword(new String(password, StandardCharsets.UTF_8));
        return storedHash.equals(providedHash);
    }

    private static String hashPassword(String password) {
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            byte[] hash = digest.digest(password.getBytes(StandardCharsets.UTF_8));
            StringBuilder hexString = new StringBuilder();
            for (byte b : hash) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) hexString.append('0');
                hexString.append(hex);
            }
            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("SHA-256 not available", e);
        }
    }
}
