package com.sentinelshield.mobile.camera

import android.Manifest
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import androidx.core.content.ContextCompat

class ThiefCameraGateway(private val context: Context) {
    fun capture(
        request: IncidentCameraRequest,
        userConsentGranted: Boolean,
        protectionArmed: Boolean,
    ): CameraCommandResult {
        request.validated()
        if (!userConsentGranted || !protectionArmed) {
            return CameraCommandResult.Rejected
        }
        if (ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA) !=
            PackageManager.PERMISSION_GRANTED
        ) {
            return CameraCommandResult.PermissionRequired
        }

        val intent = Intent(context, IncidentCameraService::class.java).apply {
            putExtra(IncidentCameraService.EXTRA_COMMAND_ID, request.commandId)
            putExtra(IncidentCameraService.EXTRA_FRONT_CAMERA, request.useFrontCamera)
            putExtra(IncidentCameraService.EXTRA_BURST_COUNT, request.burstCount)
            putExtra(IncidentCameraService.EXTRA_INCIDENT_TYPE, request.incidentType)
            request.latitude?.let { putExtra(IncidentCameraService.EXTRA_LATITUDE, it) }
            request.longitude?.let { putExtra(IncidentCameraService.EXTRA_LONGITUDE, it) }
        }

        return try {
            ContextCompat.startForegroundService(context, intent)
            CameraCommandResult.Accepted
        } catch (_: RuntimeException) {
            CameraCommandResult.ForegroundStartNotAllowed
        }
    }
}

enum class CameraCommandResult {
    Accepted,
    Rejected,
    PermissionRequired,
    ForegroundStartNotAllowed,
}
