package com.gestoreasy.services

import android.content.Context
import android.content.Intent
import android.net.Uri
import com.gestoreasy.database.entities.Client

/**
 * Serviço para gerenciamento de rotas
 */
class RouteService(private val context: Context) {
    
    /**
     * Abre Google Maps com rota para o cliente
     */
    fun openRouteToClient(client: Client) {
        val address = buildString {
            if (client.endereco != null) append(client.endereco)
            if (client.cidade != null) {
                if (isNotEmpty()) append(", ")
                append(client.cidade)
            }
            if (client.estado != null) {
                if (isNotEmpty()) append(" - ")
                append(client.estado)
            }
        }
        
        if (address.isNotEmpty()) {
            val uri = Uri.parse("google.navigation:q=${Uri.encode(address)}")
            val intent = Intent(Intent.ACTION_VIEW, uri)
            intent.setPackage("com.google.android.apps.maps")
            
            if (intent.resolveActivity(context.packageManager) != null) {
                context.startActivity(intent)
            } else {
                // Fallback para navegador
                val webUri = Uri.parse("https://www.google.com/maps/dir/?api=1&destination=${Uri.encode(address)}")
                context.startActivity(Intent(Intent.ACTION_VIEW, webUri))
            }
        }
    }
    
    /**
     * Abre Google Maps com múltiplos destinos (rota otimizada)
     */
    fun openOptimizedRoute(clients: List<Client>) {
        if (clients.isEmpty()) return
        
        val waypoints = clients.joinToString("|") { client ->
            buildString {
                if (client.endereco != null) append(client.endereco)
                if (client.cidade != null) {
                    if (isNotEmpty()) append(", ")
                    append(client.cidade)
                }
                if (client.estado != null) {
                    if (isNotEmpty()) append(" - ")
                    append(client.estado)
                }
            }
        }
        
        val uri = Uri.parse("https://www.google.com/maps/dir/?api=1&waypoints=${Uri.encode(waypoints)}&optimize=true")
        val intent = Intent(Intent.ACTION_VIEW, uri)
        
        if (intent.resolveActivity(context.packageManager) != null) {
            context.startActivity(intent)
        }
    }
    
    /**
     * Calcula distância entre duas coordenadas (Haversine)
     */
    fun calculateDistance(
        lat1: Double,
        lon1: Double,
        lat2: Double,
        lon2: Double
    ): Double {
        val earthRadius = 6371.0 // km
        
        val dLat = Math.toRadians(lat2 - lat1)
        val dLon = Math.toRadians(lon2 - lon1)
        
        val a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
                Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) *
                Math.sin(dLon / 2) * Math.sin(dLon / 2)
        
        val c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a))
        
        return earthRadius * c
    }
}

