package br.gov.extrema.agenteti.ui

import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import br.gov.extrema.agenteti.databinding.ActivityMainBinding
import br.gov.extrema.agenteti.device.DeviceCollector
import br.gov.extrema.agenteti.repository.AgentRepository
import br.gov.extrema.agenteti.worker.SyncScheduler
import com.google.android.material.snackbar.Snackbar
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class MainActivity : AppCompatActivity() {
    private lateinit var binding: ActivityMainBinding
    private lateinit var repository: AgentRepository
    private val scope = CoroutineScope(SupervisorJob()+Dispatchers.Main)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState);binding=ActivityMainBinding.inflate(layoutInflater);setContentView(binding.root);repository=AgentRepository(this)
        binding.server.setText("https://extrema.dev.br/manutencao_ti/api/tablets")
        binding.activateButton.setOnClickListener { activate() };binding.syncButton.setOnClickListener { sync() };binding.infoButton.setOnClickListener { showDeviceInfo() };binding.diagnosticButton.setOnClickListener { diagnose() }
        render()
    }

    private fun render() {
        val active=repository.activated();binding.activationPanel.visibility=if(active)View.GONE else View.VISIBLE;binding.activePanel.visibility=if(active)View.VISIBLE else View.GONE
        if(active){val state=repository.state();binding.agentId.text=state.agentId;binding.patrimonyValue.text=state.patrimony;binding.modelValue.text=state.model;binding.lastSyncValue.text=state.lastSync;binding.statusValue.text=state.status;SyncScheduler.schedule(this)}
    }

    private fun activate(){setBusy(true);scope.launch {try{withContext(Dispatchers.IO){repository.activate(binding.server.text.toString().trim(),binding.activationCode.text.toString().trim(),binding.patrimony.text.toString().trim(),binding.responsible.text.toString().trim(),binding.department.text.toString().trim(),binding.serial.text.toString().trim(),binding.imei.text.toString().trim(),binding.notes.text.toString().trim());repository.sync()};message("Inventário ativado com sucesso.");render()}catch(error:Exception){message(error.message?:"Falha na ativação.")}finally{setBusy(false)}}}
    private fun sync(){setBusy(true);scope.launch {try{withContext(Dispatchers.IO){repository.sync()};message("Inventário sincronizado.");render()}catch(error:Exception){message(error.message?:"Falha na sincronização.")}finally{setBusy(false)}}}
    private fun diagnose(){setBusy(true);scope.launch {try{val result=withContext(Dispatchers.IO){repository.diagnose()};AlertDialog.Builder(this@MainActivity).setTitle("Diagnóstico de conexão").setMessage("HTTPS: válido\nServidor: acessível\nAgente: ${result.optString("status")}\nHorário do servidor: ${result.optString("server_time")}").setPositiveButton("OK",null).show()}catch(error:Exception){AlertDialog.Builder(this@MainActivity).setTitle("Diagnóstico de conexão").setMessage(error.message?:"Servidor indisponível.").setPositiveButton("OK",null).show()}finally{setBusy(false)}}}
    private fun showDeviceInfo(){val data=DeviceCollector.collect(this,false);AlertDialog.Builder(this).setTitle("Informações do dispositivo").setMessage("${data.optString("manufacturer")} ${data.optString("model")}\nAndroid ${data.optString("android_version")} • API ${data.optInt("sdk_int")}\nRAM: ${data.optLong("ram_total_mb")/1024.0} GB\nArmazenamento: ${data.optLong("storage_total_mb")/1024.0} GB\nBateria: ${data.optInt("battery_percent")}%\nRede: ${data.optString("network_type")}\nIP: ${data.optString("local_ip")}").setPositiveButton("OK",null).show()}
    private fun setBusy(busy:Boolean){binding.progress.visibility=if(busy)View.VISIBLE else View.GONE;binding.activateButton.isEnabled=!busy;binding.syncButton.isEnabled=!busy;binding.diagnosticButton.isEnabled=!busy}
    private fun message(text:String)=Snackbar.make(binding.root,text,Snackbar.LENGTH_LONG).show()
    override fun onDestroy(){scope.cancel();super.onDestroy()}
}
