package com.parentalmonitor.child.services;

import android.app.*;
import android.content.*;
import android.os.*;
import androidx.core.app.NotificationCompat;
import com.parentalmonitor.child.api.ApiClient;
import com.parentalmonitor.child.utils.DeviceInfoCollector;
import com.parentalmonitor.child.utils.PermissionTracker;
import org.json.JSONObject;

public class SyncService extends Service {
    private static final String CHANNEL_ID = "sync_channel";
    private static final int NOTIFICATION_ID = 1001;
    private Handler handler;
    private Runnable syncRunnable;
    private static final long SYNC_INTERVAL = 15000;

    @Override
    public void onCreate() {
        super.onCreate();
        createNotificationChannel();
        handler = new Handler(Looper.getMainLooper());
        syncRunnable = new Runnable() {
            @Override
            public void run() {
                performSync();
                handler.postDelayed(this, SYNC_INTERVAL);
            }
        };
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
            .setContentTitle("Child Monitor")
            .setContentText("Monitoring active")
            .setSmallIcon(android.R.drawable.ic_dialog_info)
            .setPriority(NotificationCompat.PRIORITY_LOW)
            .build();
        startForeground(NOTIFICATION_ID, notification);
        handler.post(syncRunnable);
        return START_STICKY;
    }

    private void performSync() {
        try {
            ApiClient api = ApiClient.getInstance(this);
            int deviceId = api.getDeviceId();
            if (deviceId == 0) return;

            JSONObject data = new JSONObject();
            data.put("device_id", deviceId);
            data.put("battery_level", DeviceInfoCollector.getBatteryLevel(this));
            data.put("is_charging", DeviceInfoCollector.isCharging(this));
            data.put("is_screen_on", DeviceInfoCollector.isScreenOn(this));
            data.put("wifi_connected", DeviceInfoCollector.isWifiConnected(this));
            data.put("mobile_data", DeviceInfoCollector.isMobileDataOn(this));
            data.put("latitude", DeviceInfoCollector.getLatitude(this));
            data.put("longitude", DeviceInfoCollector.getLongitude(this));
            data.put("storage_used", DeviceInfoCollector.getStorageUsed());
            data.put("storage_total", DeviceInfoCollector.getStorageTotal());
            data.put("ram_used", DeviceInfoCollector.getRamUsed(this));
            data.put("ram_total", DeviceInfoCollector.getRamTotal(this));
            data.put("permissions", PermissionTracker.getPermissionStatus(this));

            JSONObject result = api.post("/api/sync", data);
            if (result.optBoolean("success")) {
                processCommands(result.optJSONObject("data"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void processCommands(JSONObject data) {
        if (data == null) return;
        try {
            if (data.has("pending_commands")) {
                // Process remote commands from parent
                CommandProcessor.process(this, data.getJSONArray("pending_commands"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(CHANNEL_ID, "Sync Service",
                NotificationManager.IMPORTANCE_LOW);
            channel.setDescription("Background monitoring service");
            getSystemService(NotificationManager.class).createNotificationChannel(channel);
        }
    }

    @Override
    public IBinder onBind(Intent intent) { return null; }

    @Override
    public void onDestroy() {
        handler.removeCallbacks(syncRunnable);
        super.onDestroy();
    }
}
