package com.eonbry.store

import android.app.AlertDialog
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.view.LayoutInflater
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.core.content.FileProvider
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import org.json.JSONObject
import java.io.BufferedInputStream
import java.io.BufferedReader
import java.io.File
import java.io.FileOutputStream
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL


fun verificarAtualizacao(context: Context) {
        CoroutineScope(Dispatchers.IO).launch {
            try {
                val url = URL("https://SEUHOST/SUAPASTA/update/versao.json")
                val conn = url.openConnection() as HttpURLConnection
                val reader = BufferedReader(InputStreamReader(conn.inputStream))
                val resposta = reader.readText()
                reader.close()

                val json = JSONObject(resposta)
                val versaoServidor = json.getString("versao")
                val mensagem = json.getString("mensagem")
                val apkUrl = json.getString("url_apk")

                val versaoAtual = context.packageManager.getPackageInfo(context.packageName, 0).versionName

                if (versaoServidor != versaoAtual) {
                    CoroutineScope(Dispatchers.Main).launch {
                        mostrarDialogAtualizacao(context, mensagem, apkUrl)
                    }
                }

            } catch (e: Exception) {
                e.printStackTrace()
                CoroutineScope(Dispatchers.Main).launch {
                    Toast.makeText(context, "Erro ao verificar atualização", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }


private fun mostrarDialogAtualizacao(context: Context, mensagem: String, apkUrl: String) {
        val dialogView = LayoutInflater.from(context).inflate(R.layout.dialog_update, null)
        val txtMensagem = dialogView.findViewById<TextView>(R.id.txtMensagem)
        val btnAtualizar = dialogView.findViewById<Button>(R.id.btnAtualizar)
        val btnCancelar = dialogView.findViewById<Button>(R.id.btnCancelar)

        txtMensagem.text = mensagem

        val dialog = AlertDialog.Builder(context)
            .setView(dialogView)
            .setCancelable(false)
            .create()

        btnAtualizar.setOnClickListener {
            dialog.dismiss()
            baixarEInstalarApk(context, apkUrl)
        }

        btnCancelar.setOnClickListener {
            dialog.dismiss()
        }

        dialog.show()
    }

    private fun baixarEInstalarApk(context: Context, urlApk: String) {
        CoroutineScope(Dispatchers.IO).launch {
            try {
                val url = URL(urlApk)
                val connection = url.openConnection() as HttpURLConnection
                connection.connect()

                val input = BufferedInputStream(url.openStream())
                val file = File(context.getExternalFilesDir(null), "update.apk")
                val output = FileOutputStream(file)

                val data = ByteArray(1024)
                var count: Int
                while (input.read(data).also { count = it } != -1) {
                    output.write(data, 0, count)
                }

                output.flush()
                output.close()
                input.close()

                val apkUri: Uri = FileProvider.getUriForFile(
                    context,
                    "com.eonbry.store.provider",
                    file
                )

                val intent = Intent(Intent.ACTION_VIEW).apply {
                    setDataAndType(apkUri, "application/vnd.android.package-archive")
                    flags = Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_ACTIVITY_NEW_TASK
                }

                context.startActivity(intent)

            } catch (e: Exception) {
                e.printStackTrace()
                CoroutineScope(Dispatchers.Main).launch {
                    Toast.makeText(context, "Erro ao baixar/instalar APK", Toast.LENGTH_LONG).show()
                }
            }
        }
    }