package com.example.projekta

import android.app.TimePickerDialog
import android.graphics.Color
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.cardview.widget.CardView
import com.android.volley.Request
import com.android.volley.toolbox.JsonObjectRequest
import com.android.volley.toolbox.StringRequest
import com.android.volley.toolbox.Volley
import java.util.Calendar
import java.util.Locale

class MetodePemupukanActivity : AppCompatActivity() {

    private lateinit var btnBack: ImageView

    private lateinit var cardAuto: CardView
    private lateinit var cardManual: CardView

    private lateinit var etInterval: EditText
    private lateinit var etDurasi: EditText

    private lateinit var tvJam: TextView

    private lateinit var btnPilihJam: Button
    private lateinit var btnSimpan: Button

    private lateinit var btnPompaManual: Button
    private lateinit var tvStatusManual: TextView

    private var mode = "otomatis"
    private var isPompaOn = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_metode_pemupukan)

        initView()
        setupListener()
        loadPengaturan()
    }

    private fun initView() {

        btnBack = findViewById(R.id.btnBack)

        cardAuto = findViewById(R.id.cardAuto)
        cardManual = findViewById(R.id.cardManual)

        etInterval = findViewById(R.id.etInterval)
        etDurasi = findViewById(R.id.etDurasi)

        tvJam = findViewById(R.id.tvJam)

        btnPilihJam = findViewById(R.id.btnPilihJam)
        btnSimpan = findViewById(R.id.btnSimpan)

        btnPompaManual = findViewById(R.id.btnPompaManual)
        tvStatusManual = findViewById(R.id.tvStatusManual)
    }

    private fun setupListener() {

        btnBack.setOnClickListener {
            finish()
        }

        cardAuto.setOnClickListener {
            setModeOtomatis()
        }

        cardManual.setOnClickListener {
            setModeManual()
        }

        btnPilihJam.setOnClickListener {

            val calendar = Calendar.getInstance()

            TimePickerDialog(
                this,
                { _, hour, minute ->

                    tvJam.text = String.format(
                        Locale.getDefault(),
                        "%02d:%02d:00",
                        hour,
                        minute
                    )
                },
                calendar.get(Calendar.HOUR_OF_DAY),
                calendar.get(Calendar.MINUTE),
                true
            ).show()
        }

        btnPompaManual.setOnClickListener {
            togglePompaManual()
        }

        btnSimpan.setOnClickListener {
            simpanPengaturan()
        }
    }

    private fun setModeOtomatis() {

        mode = "otomatis"

        etInterval.isEnabled = true
        etDurasi.isEnabled = true
        btnPilihJam.isEnabled = true

        cardAuto.cardElevation = 12f
        cardManual.cardElevation = 4f
    }

    private fun setModeManual() {

        mode = "manual"

        etInterval.isEnabled = false
        etDurasi.isEnabled = false
        btnPilihJam.isEnabled = false

        cardAuto.cardElevation = 4f
        cardManual.cardElevation = 12f
    }

    private fun togglePompaManual() {

        if (mode != "manual") {

            Toast.makeText(
                this,
                "Pilih MODE MANUAL terlebih dahulu",
                Toast.LENGTH_SHORT
            ).show()

            return
        }

        isPompaOn = !isPompaOn

        if (isPompaOn) {

            tvStatusManual.text = "STATUS: ON"
            tvStatusManual.setTextColor(
                Color.parseColor("#2E7D32")
            )

            btnPompaManual.text = "MATIKAN POMPA"
            btnPompaManual.setBackgroundColor(
                Color.parseColor("#D32F2F")
            )

            simpanHistori("manual", "ON")

        } else {

            tvStatusManual.text = "STATUS: OFF"
            tvStatusManual.setTextColor(
                Color.parseColor("#D32F2F")
            )

            btnPompaManual.text = "NYALAKAN POMPA"
            btnPompaManual.setBackgroundColor(
                Color.parseColor("#2E7D32")
            )

            simpanHistori("manual", "OFF")
        }
    }

    private fun simpanPengaturan() {

        if (mode == "otomatis") {

            if (etInterval.text.toString().trim().isEmpty()) {
                etInterval.error = "Isi interval hari"
                return
            }

            if (etDurasi.text.toString().trim().isEmpty()) {
                etDurasi.error = "Isi durasi detik"
                return
            }
        }

        val url =
            "http://192.168.43.191/projekta/save_pengaturan.php"

        val request = object : StringRequest(
            Method.POST,
            url,

            { response ->

                Toast.makeText(
                    this,
                    response,
                    Toast.LENGTH_SHORT
                ).show()
            },

            {

                Toast.makeText(
                    this,
                    "Gagal koneksi server",
                    Toast.LENGTH_SHORT
                ).show()
            }
        ) {

            override fun getParams(): MutableMap<String, String> {

                val params = HashMap<String, String>()

                params["mode"] = mode

                if (mode == "otomatis") {

                    params["interval_hari"] =
                        etInterval.text.toString().trim()

                    params["durasi"] =
                        etDurasi.text.toString().trim()

                    params["jam"] =
                        tvJam.text.toString()

                } else {

                    params["status_manual"] =
                        if (isPompaOn) "ON" else "OFF"
                }

                return params
            }
        }

        Volley.newRequestQueue(this)
            .add(request)
    }

    private fun simpanHistori(
        modePemupukan: String,
        statusPompa: String
    ) {

        val url =
            "http://192.168.43.191/projekta/insert_histori.php"

        val request = object : StringRequest(
            Request.Method.POST,
            url,
            {},
            {}
        ) {

            override fun getParams(): MutableMap<String, String> {

                val params = HashMap<String, String>()

                params["mode"] = modePemupukan

                params["status"] = statusPompa

                return params
            }
        }

        Volley.newRequestQueue(this)
            .add(request)

    }

    private fun loadPengaturan() {

        val url =
            "http://192.168.43.191/projekta/get_pengaturan.php"

        val request = JsonObjectRequest(
            Request.Method.GET,
            url,
            null,

            { response ->

                try {

                    if (response.getBoolean("success")) {

                        mode =
                            response.getString("mode")

                        val interval =
                            response.getInt("interval_hari")

                        val durasi =
                            response.getInt("durasi")

                        val jam =
                            response.getString("jam")

                        val statusManual =
                            response.getString("status_manual")

                        tvJam.text = jam

                        etInterval.setText(
                            interval.toString()
                        )

                        etDurasi.setText(
                            durasi.toString()
                        )

                        if (mode == "manual") {

                            setModeManual()

                            if (statusManual == "ON") {

                                isPompaOn = true

                                tvStatusManual.text =
                                    "STATUS: ON"

                                tvStatusManual.setTextColor(
                                    Color.parseColor("#2E7D32")
                                )

                                btnPompaManual.text =
                                    "MATIKAN POMPA"

                                btnPompaManual.setBackgroundColor(
                                    Color.parseColor("#D32F2F")
                                )

                            } else {

                                isPompaOn = false

                                tvStatusManual.text =
                                    "STATUS: OFF"

                                tvStatusManual.setTextColor(
                                    Color.parseColor("#D32F2F")
                                )

                                btnPompaManual.text =
                                    "NYALAKAN POMPA"

                                btnPompaManual.setBackgroundColor(
                                    Color.parseColor("#2E7D32")
                                )
                            }

                        } else {

                            setModeOtomatis()
                        }
                    }

                } catch (e: Exception) {

                    setModeOtomatis()
                }
            },

            {

                setModeOtomatis()
            }
        )

        Volley.newRequestQueue(this)
            .add(request)
    }
}