package com.hs.sosnow;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.hardware.Camera;
import android.media.CamcorderProfile;
import android.media.MediaRecorder;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.view.SurfaceView;

import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;

import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;

@SuppressWarnings("deprecation")
public class VideoRecordService extends Service {

    private Camera camera;
    private MediaRecorder mediaRecorder;
    private File videoFile;
    private SurfaceView dummySurface;
    private double currentLat = 0, currentLng = 0;

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent != null) {
            currentLat = intent.getDoubleExtra("LATITUDE", 0);
            currentLng = intent.getDoubleExtra("LONGITUDE", 0);
        }

        startForegroundNotification();
        initBackgroundRecording();
        return START_NOT_STICKY;
    }

    private void startForegroundNotification() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel chan = new NotificationChannel("SOS_VID", "Emergency Recording", NotificationManager.IMPORTANCE_LOW);
            NotificationManager mgr = getSystemService(NotificationManager.class);
            if (mgr != null) mgr.createNotificationChannel(chan);
        }
        Notification notification = new NotificationCompat.Builder(this, "SOS_VID")
                .setContentTitle("Emergency Evidence Capture")
                .setContentText("Securing tamper-proof incident recording")
                .setSmallIcon(android.R.drawable.ic_menu_camera)
                .build();
        startForeground(2002, notification);
    }

    private void initBackgroundRecording() {
        try {
            camera = Camera.open(Camera.CameraInfo.CAMERA_FACING_BACK);
            camera.unlock();

            dummySurface = new SurfaceView(this);
            mediaRecorder = new MediaRecorder();
            mediaRecorder.setCamera(camera);
            mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
            mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
            mediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_480P));

            File outputDir = getExternalFilesDir(null);
            videoFile = new File(outputDir, "SOS_EVIDENCE_" + System.currentTimeMillis() + ".mp4");
            mediaRecorder.setOutputFile(videoFile.getAbsolutePath());
            mediaRecorder.setPreviewDisplay(dummySurface.getHolder().getSurface());

            mediaRecorder.prepare();
            mediaRecorder.start();

            // Record for 10 seconds, then stop and push to cloud
            new Handler(Looper.getMainLooper()).postDelayed(this::finishAndUpload, 10000);

        } catch (Exception e) {
            stopSelf();
        }
    }

    private void finishAndUpload() {
        try {
            if (mediaRecorder != null) {
                mediaRecorder.stop();
                mediaRecorder.release();
            }
            if (camera != null) {
                camera.release();
            }
        } catch (Exception ignored) {}

        if (videoFile != null && videoFile.exists()) {
            new Thread(() -> {
                String sha256 = generateFileSHA256(videoFile);
                uploadEvidenceToServer(videoFile, sha256, currentLat, currentLng);
                stopSelf();
            }).start();
        } else {
            stopSelf();
        }
    }

    private String generateFileSHA256(File file) {
        try (FileInputStream fis = new FileInputStream(file)) {
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            byte[] buffer = new byte[8192];
            int read;
            while ((read = fis.read(buffer)) != -1) {
                digest.update(buffer, 0, read);
            }
            byte[] hashBytes = digest.digest();
            StringBuilder sb = new StringBuilder();
            for (byte b : hashBytes) {
                sb.append(String.format("%02x", b));
            }
            return sb.toString();
        } catch (Exception e) {
            return "";
        }
    }

    private void uploadEvidenceToServer(File file, String hash, double lat, double lng) {
        SharedPreferences prefs = getSharedPreferences("SosNowPrefs", Context.MODE_PRIVATE);
        String token = prefs.getString("AUTH_TOKEN", "");
        if (token.isEmpty()) return;

        String boundary = "===" + System.currentTimeMillis() + "===";
        try {
            URL url = new URL(AppConfig.SERVER_BASE_URL + "?action=upload_emergency_evidence");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
            conn.setRequestProperty("Authorization", token);

            try (OutputStream os = conn.getOutputStream();
                 PrintWriter writer = new PrintWriter(os, true)) {

                // Latitude
                writer.append("--").append(boundary).append("\r\n");
                writer.append("Content-Disposition: form-data; name=\"latitude\"\r\n\r\n").append(String.valueOf(lat)).append("\r\n");

                // Longitude
                writer.append("--").append(boundary).append("\r\n");
                writer.append("Content-Disposition: form-data; name=\"longitude\"\r\n\r\n").append(String.valueOf(lng)).append("\r\n");

                // SHA-256 Hash
                writer.append("--").append(boundary).append("\r\n");
                writer.append("Content-Disposition: form-data; name=\"video_sha256\"\r\n\r\n").append(hash).append("\r\n");

                // Video File Binary
                writer.append("--").append(boundary).append("\r\n");
                writer.append("Content-Disposition: form-data; name=\"video\"; filename=\"").append(file.getName()).append("\"\r\n");
                writer.append("Content-Type: video/mp4\r\n\r\n");
                writer.flush();

                try (FileInputStream fis = new FileInputStream(file)) {
                    byte[] buffer = new byte[4096];
                    int len;
                    while ((len = fis.read(buffer)) != -1) {
                        os.write(buffer, 0, len);
                    }
                    os.flush();
                }

                writer.append("\r\n").append("--").append(boundary).append("--\r\n");
                writer.flush();
            }

            conn.getResponseCode();
        } catch (Exception ignored) {}
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) { return null; }
}