package com.example.petstoremobile.utils;

import android.content.Context;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class ActivityLogger {

    private static final String LOG_FILE = "log.txt";

    // Logs a general message with a timestamp
    public static void log(Context context, String message) {
        String timestamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()).format(new Date());
        String entry = timestamp + " | INFO | " + message + "\n";
        writeToFile(context, entry);
    }

    // Logs a database change (ADD, UPDATE, DELETE) with entity type and ID
    public static void logChange(Context context, String entity, String action, int id) {
        String timestamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()).format(new Date());
        String entry = timestamp + " | DB CHANGE | " + action + " " + entity + " ID: " + id + "\n";
        writeToFile(context, entry);
    }

    // Logs an exception with location info
    public static void logException(Context context, String location, Exception e) {
        String timestamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()).format(new Date());
        String entry = timestamp + " | ERROR | " + location + ": " + e.getMessage() + "\n";
        writeToFile(context, entry);
    }

    // Writes the log entry to log.txt in internal storage
    private static void writeToFile(Context context, String entry) {
        try {
            FileWriter fw = new FileWriter(context.getFilesDir() + "/" + LOG_FILE, true);
            fw.write(entry);
            fw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
