package com.example.projekta

import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.util.Log
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.hivemq.client.mqtt.MqttClient
import com.hivemq.client.mqtt.mqtt3.Mqtt3AsyncClient
import org.json.JSONObject
import kotlin.math.roundToInt

class PemupukanActivity : AppCompatActivity() {

    private lateinit var tvSuhuUdara: TextView
    private lateinit var tvKelembapanUdara: TextView
    private lateinit var tvSuhuTanah: TextView
    private lateinit var tvKelembapanTanah: TextView
    private lateinit var tvStatusTanah: TextView
    private lateinit var tvStatusSistem: TextView
    private lateinit var tvStatusPompa: TextView

    private lateinit var mqttClient: Mqtt3AsyncClient

    private val mqttUser = "DeaBaasithian"
    private val mqttPassword = "Lekmamok123#"

    private val topicSensor =
        "pemupukan/sensor"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContentView(
            R.layout.activity_pemupukan
        )

        val btnBack =
            findViewById<ImageView>(
                R.id.btnBack
            )

        val btnMetode =
            findViewById<Button>(
                R.id.btnMetode
            )

        tvSuhuUdara =
            findViewById(
                R.id.tvSuhuUdara
            )

        tvKelembapanUdara =
            findViewById(
                R.id.tvKelembapanUdara
            )

        tvSuhuTanah =
            findViewById(
                R.id.tvSuhuTanah
            )

        tvKelembapanTanah =
            findViewById(
                R.id.tvKelembapanTanah
            )

        tvStatusTanah =
            findViewById(
                R.id.tvStatusTanah
            )

        tvStatusSistem =
            findViewById(
                R.id.tvStatusSistem
            )

        tvStatusPompa =
            findViewById(
                R.id.tvStatusPompa
            )

        btnBack.setOnClickListener {
            finish()
        }

        btnMetode.setOnClickListener {
            startActivity(
                Intent(
                    this,
                    MetodePemupukanActivity::class.java
                )
            )
        }

        tampilDataKosong()

        connectMQTT()
    }

    private fun tampilDataKosong() {

        tvSuhuTanah.text =
            "🌡️ Suhu Tanah: --"

        tvKelembapanTanah.text =
            "🌱 Kelembapan Tanah: --"

        tvSuhuUdara.text =
            "☀️ Suhu Udara: --"

        tvKelembapanUdara.text =
            "💦 Kelembapan Udara: --"

        tvStatusTanah.text =
            "🟢 Status Tanah: --"

        tvStatusSistem.text =
            "⚙️ Menyambungkan..."

        tvStatusPompa.text =
            "🚰 Status Pompa: --"
    }

    private fun connectMQTT() {

        mqttClient =
            MqttClient.builder()

                .useMqttVersion3()

                .identifier(
                    "android_" +
                            System.currentTimeMillis()
                )

                .serverHost(
                    "09c34b6317bd4610829ec8a206e9da43.s1.eu.hivemq.cloud"
                )

                .serverPort(
                    8883
                )

                .sslWithDefaultConfig()

                .buildAsync()

        mqttClient.connectWith()

            .simpleAuth()

            .username(
                mqttUser
            )

            .password(
                mqttPassword.toByteArray()
            )

            .applySimpleAuth()

            .send()

            .whenComplete { _, error ->

                runOnUiThread {

                    if (error == null) {

                        tvStatusSistem.text =
                            "⚙️ MQTT Connected"

                        Log.d(
                            "MQTT",
                            "CONNECT OK"
                        )

                        subscribeSensor()

                    } else {

                        tvStatusSistem.text =
                            "⚙️ Connect Failed"

                        Log.e(
                            "MQTT",
                            error.stackTraceToString()
                        )
                    }
                }
            }
    }

    private fun subscribeSensor() {

        mqttClient.subscribeWith()

            .topicFilter(
                topicSensor
            )

            .callback { publish ->

                try {

                    val payload =
                        String(
                            publish.payloadAsBytes
                        )

                    Log.d(
                        "MQTT_DATA",
                        payload
                    )

                    val json =
                        JSONObject(
                            payload
                        )

                    runOnUiThread {

                        tvSuhuTanah.text =
                            "🌡️ Suhu Tanah: ${
                                json.optDouble(
                                    "suhu_tanah",
                                    0.0
                                ).roundToInt()
                            }°C"

                        tvKelembapanTanah.text =
                            "🌱 Kelembapan Tanah: ${
                                json.optInt(
                                    "kelembapan_tanah",
                                    0
                                )
                            }%"

                        tvSuhuUdara.text =
                            "☀️ Suhu Udara: ${
                                json.optDouble(
                                    "suhu_udara",
                                    0.0
                                ).roundToInt()
                            }°C"

                        tvKelembapanUdara.text =
                            "💦 Kelembapan Udara: ${
                                json.optDouble(
                                    "kelembapan_udara",
                                    0.0
                                ).roundToInt()
                            }%"

                        tvStatusTanah.text =
                            "🟢 Status Tanah: ${
                                json.optString(
                                    "status_tanah",
                                    "-"
                                )
                            }"

                        val statusPompa =
                            json.optString(
                                "status_pompa",
                                "OFF"
                            )

                        tvStatusPompa.text =
                            "🚰 Status Pompa: $statusPompa"

                        if (
                            statusPompa.equals(
                                "ON",
                                true
                            )
                        ) {
                            tvStatusPompa.setTextColor(
                                Color.GREEN
                            )
                        } else {
                            tvStatusPompa.setTextColor(
                                Color.RED
                            )
                        }

                        tvStatusSistem.text =
                            "⚙️ Data Realtime"
                    }

                } catch (e: Exception) {

                    Log.e(
                        "JSON",
                        e.stackTraceToString()
                    )
                }

            }

            .send()

            .whenComplete { _, error ->

                runOnUiThread {

                    if (error == null) {

                        Log.d(
                            "MQTT",
                            "SUBSCRIBE OK"
                        )

                    } else {

                        tvStatusSistem.text =
                            "⚙️ Subscribe Failed"

                        Log.e(
                            "MQTT",
                            error.stackTraceToString()
                        )
                    }

                }

            }

    }

    override fun onDestroy() {

        super.onDestroy()

        if (::mqttClient.isInitialized) {

            mqttClient.disconnect()
        }
    }
}