package br.gov.extrema.agenteti.repository

import android.content.Context
import br.gov.extrema.agenteti.data.AgentState
import br.gov.extrema.agenteti.device.DeviceCollector
import br.gov.extrema.agenteti.network.ApiClient
import br.gov.extrema.agenteti.security.SecureStore
import br.gov.extrema.agenteti.worker.SyncScheduler
import org.json.JSONObject
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale

class AgentRepository(private val context: Context) {
    private val store = SecureStore(context);private val api = ApiClient(context)
    fun activated() = store.isActivated()
    fun state() = AgentState(store.get("agent_id"), store.get("patrimonio"), android.os.Build.MODEL, store.get("last_sync", "Ainda não realizada"), store.get("status", "ATIVO"), br.gov.extrema.agenteti.BuildConfig.VERSION_NAME)

    fun activate(server:String, code:String, patrimony:String, responsible:String, department:String, serial:String, imei:String, notes:String): JSONObject {
        require(server.startsWith("https://")) { "Informe um endereço HTTPS." };require(code.matches(Regex("[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}"))) { "Código de ativação inválido." }
        require(patrimony.isNotBlank()&&responsible.isNotBlank()&&department.isNotBlank()) { "Patrimônio, responsável e setor são obrigatórios." }
        store.put("server",server.trimEnd('/'))
        val payload=DeviceCollector.collect(context,false).put("activation_code",code.uppercase()).put("patrimonio",patrimony.trim()).put("responsavel_nome",responsible.trim()).put("setor",department.trim()).put("numero_serie_manual",serial.trim()).put("imei_manual",imei.trim()).put("observacoes",notes.trim())
        val response=api.post("registrar.php",payload,false);store.put("agent_id",response.getString("agent_id"));store.put("token",response.getString("token"));store.put("patrimonio",patrimony.trim());store.put("responsavel",responsible.trim());store.put("setor",department.trim());applyConfig(response);SyncScheduler.schedule(context);return response
    }

    fun sync(): JSONObject {val response=api.post("sincronizar.php",DeviceCollector.collect(context,store.getInt("collect_apps",1)==1),true);store.put("last_sync",SimpleDateFormat("dd/MM/yyyy HH:mm",Locale.getDefault()).format(Date()));store.put("status","ATIVO");applyConfig(response);SyncScheduler.schedule(context);return response}
    fun diagnose(): JSONObject = api.post("status.php",JSONObject(),true).also(::applyConfig)
    private fun applyConfig(response:JSONObject){store.putInt("sync_interval",response.optInt("sync_interval_min",30));store.putInt("collect_apps",if(response.optBoolean("collect_apps",true))1 else 0);if(response.has("tracked_apps"))store.put("tracked_apps",response.getJSONArray("tracked_apps").toString())}
}
