package com.example.uitugasakhir.ViewModel

import android.util.Log
import androidx.compose.runtime.*
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.uitugasakhir.api.RetrofitClient
import com.example.uitugasakhir.model.*
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

import android.content.Context
import com.android.volley.Request
import com.android.volley.toolbox.StringRequest
import com.android.volley.toolbox.Volley
import com.example.uitugasakhir.model.RiwayatItem
import org.json.JSONArray
import org.json.JSONObject

import java.text.SimpleDateFormat
import java.util.*
import android.app.Activity
import java.util.Locale

import android.widget.Toast

import com.example.uitugasakhir.SensorNotification
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.asSharedFlow

import com.example.uitugasakhir.mqtt.MqttManager




class SensorViewModel : ViewModel() {

    var warningData by mutableStateOf<WarningResponse?>(null)

    var notifTanahAktif by mutableStateOf(true)
        private set

    var notifHujanAktif by mutableStateOf(true)
        private set

    var buzzerAktif by mutableStateOf(true)
        private set

    var warningList = mutableStateListOf<WarningItem>()
        private set

    // =========================
    var selectedItems by mutableStateOf<Set<Int>>(emptySet())
        private set

    var status by mutableStateOf("Aman")
        private set

    var keterangan by mutableStateOf("Semua kondisi normal")
        private set

    var data by mutableStateOf<Sensor?>(null)
        private set

    var isLoading by mutableStateOf(false)
        private set

    var currentAmbang by mutableStateOf<AmbangBatas?>(null)
        private set

    var manualWarningMessage by mutableStateOf("")
        private set

    var autoWarningMessage by mutableStateOf("")
        private set

    var isManualWarningActive by mutableStateOf(false)
        private set

    var isAutoWarningActive by mutableStateOf(false)
        private set

    private var lastTriggerTime = 0L
    private var lastWarningMessages = emptySet<String>()

    var currentMode by mutableStateOf("Manual")
        private set



    fun getWarningData() {

        viewModelScope.launch {

            try {

                warningData =
                    RetrofitClient.api.getWarning()

            } catch (e: Exception) {

                e.printStackTrace()
            }
        }
    }

    private val _pumpStatus = mutableStateOf("OFF")

    fun matikanAlarm() {

        viewModelScope.launch {

            try {

                RetrofitClient.api.acknowledgeWarning()

                getWarningData()

            } catch (e: Exception) {

                e.printStackTrace()
            }
        }
    }

    fun kirimWarning(pesan: String) {

        viewModelScope.launch {

            try {

                RetrofitClient.api.insertWarning(pesan)

            } catch (e: Exception) {

                e.printStackTrace()
            }
        }
    }

    fun setNotifTanah(enabled: Boolean) {
        notifTanahAktif = enabled
    }

    fun setNotifHujan(enabled: Boolean) {
        notifHujanAktif = enabled
    }

    fun setBuzzer(enabled: Boolean) {
        buzzerAktif = enabled
    }

    fun setMode(mode: String) {
        currentMode = mode
    }

    var unreadCount by mutableStateOf(0)
        private set

    fun loadUnreadCount() {

        viewModelScope.launch {

            try {

                val response =
                    RetrofitClient.api.getUnreadCount()

                unreadCount = response.total

            } catch (e: Exception) {

                Log.e(
                    "UNREAD",
                    e.message.toString()
                )
            }
        }
    }

    fun readNotification(id: Int) {

        viewModelScope.launch {

            try {

                RetrofitClient.api.readNotification(id)

                loadUnreadCount()

            } catch (e: Exception) {

                Log.e(
                    "READ_NOTIF",
                    e.message.toString()
                )
            }
        }
    }

    fun readAllNotifications() {

        viewModelScope.launch {

            try {

                RetrofitClient.api.readAllNotifications()

                unreadCount = 0

            } catch (e: Exception) {

                Log.e(
                    "READ_ALL",
                    e.message.toString()
                )
            }
        }
    }

    // =========================
    // FIX: trigger warning
    // =========================
    private fun triggerWarning(
        message: String,
        mode: String
    ) {

        val now = System.currentTimeMillis()

        if (now - lastTriggerTime < 3000) return
        lastTriggerTime = now

        val newItem = WarningItem(
            id = 0,
            status = "warning",
            message = message,
            time = now,
            mode = mode
        )

        if (warningList.none { it.message == message }) {
            warningList.add(0, newItem)
        }

        if (warningList.size > 20) {
            warningList.removeLast()
        }

        // =========================
        // TAMBAHAN PENTING
        // =========================
        kirimWarning(message)

        getWarningData()

        // =========================

        data?.let { sensor ->
            currentAmbang?.let { ambang ->
                sendLogToServer(
                    listOf(message),
                    sensor,
                    ambang
                )
            }
        }
    }

    fun clearWarning(mode: String) {

        if (mode == "Manual") {
            isManualWarningActive = false
            manualWarningMessage = ""
        } else {
            isAutoWarningActive = false
            autoWarningMessage = ""
        }
    }

    // =========================
    // SENSOR LOOP
    // =========================
    fun getData(context: Context) {
        viewModelScope.launch {
            while (true) {
                isLoading = true

                try {
                    val sensorResponse = RetrofitClient.api.getSensor()
                    val ambangResponse = RetrofitClient.api.getAmbangBatas()

                    val sensorData = Sensor(
                        kelembaban_udara = sensorResponse.kelembaban_udara.toFloat(),
                        suhu_udara = sensorResponse.suhu_udara.toFloat(),
                        kelembaban_tanah = sensorResponse.kelembaban_tanah.toFloat(),
                        intensitas_hujan = sensorResponse.intensitas_hujan.toFloat()
                    )

                    val ambangData = AmbangBatas(
                        min_tanah = ambangResponse.min_tanah,
                        max_tanah = ambangResponse.max_tanah,
                        critical_tanah = ambangResponse.critical_tanah,
                        min_suhu = ambangResponse.min_suhu,
                        max_suhu = ambangResponse.max_suhu,
                        min_udara = ambangResponse.min_udara,
                        max_udara = ambangResponse.max_udara
                    )

                    data = sensorData
                    currentAmbang = ambangData

                    if (currentMode == "Otomatis") {

                        checkWarning(
                            context,
                            sensorData,
                            ambangData,
                            currentMode
                        )

                    } else {

                        isManualWarningActive = false
                        manualWarningMessage = ""

                        isAutoWarningActive = false
                        autoWarningMessage = ""
                    }

                } catch (e: Exception) {
                    Log.e("API", "Error: ${e.message}")
                }

                isLoading = false
                delay(5000)
            }
        }
    }

    // =========================
    // CHECK WARNING
    // =========================
    private fun checkWarning(
        context: Context,
        sensor: Sensor,
        ambang: AmbangBatas,
        mode: String
    ) {

        val messages = mutableListOf<String>()

        when {
            sensor.kelembaban_tanah < ambang.min_tanah ->
                messages.add(
                    "Kelembapan tanah < ambang (kering).\nPompa hidup otomatis"
                )

            sensor.kelembaban_tanah > ambang.max_tanah ->
                messages.add("Kelembapan tanah > ambang (lembab).\nPompa mati otomatis")
        }

        when {
            sensor.suhu_udara < ambang.min_suhu ->
                messages.add("Suhu udara < ambang (dingin).\nKondisi tanaman perlu diperhatikan")

            sensor.suhu_udara > ambang.max_suhu ->
                messages.add("Suhu udara > ambang (panas).\nKondisi tanaman perlu diperhatikan")
        }

        when {
            sensor.kelembaban_udara < ambang.min_udara ->
                messages.add("Kelembapan udara < ambang (kering).\nKondisi tanaman perlu diperhatikan")

            sensor.kelembaban_udara > ambang.max_udara ->
                messages.add("Kelembapan udara > ambang (lembab).\nKondisi tanaman perlu diperhatikan")
        }

        if (messages.isNotEmpty()) {

            SensorNotification.showNotification(
                context,
                "Peringatan Sensor",
                messages.first()
            )

            status = "Monitoring"
            keterangan = messages.first()

            if (mode == "Manual") {

                manualWarningMessage =
                    "${messages.joinToString("\n")}"

                isManualWarningActive = true

            } else {

                autoWarningMessage =
                    "${messages.joinToString("\n")}"

                isAutoWarningActive = true

                Log.d("POPUP_DEBUG", "AUTO ACTIVE = $isAutoWarningActive")
                Log.d("POPUP_DEBUG", "MESSAGE = $autoWarningMessage")
            }

            val currentWarnings = messages.toSet()

            (currentWarnings - lastWarningMessages).forEach {
                triggerWarning(it, mode)
            }

            lastWarningMessages = currentWarnings

        } else {
            lastWarningMessages = emptySet()
            status = "Aman"
            if (mode == "Manual") {

                manualWarningMessage = ""
                isManualWarningActive = false

            } else {

                autoWarningMessage = ""
                isAutoWarningActive = false
            }
            keterangan = "Semua kondisi normal"
        }
    }

    // =========================
    // DELETE (FIX STABLE UI)
    // =========================
    fun deleteWarning(item: WarningItem) {
        viewModelScope.launch {

            Log.d("DELETE_SINGLE", "CLICK DELETE ID=${item.id}")

            warningList.removeIf { it.id == item.id }

            try {
                val response = RetrofitClient.api.deleteLog(item.id)

                Log.d("DELETE_SINGLE", "RESPONSE=${response.code()}")

            } catch (e: Exception) {
                Log.e("DELETE_SINGLE", "ERROR=${e.message}")
            }
        }
    }

    fun deleteAllWarnings() {
        viewModelScope.launch {

            Log.d("DELETE_ALL", "START deleteAllWarnings")
            Log.d("DELETE_ALL", "TOTAL LIST = ${warningList.size}")

            val tempList = warningList.toList()

            if (tempList.isEmpty()) {
                Log.d("DELETE_ALL", "LIST KOSONG - STOP")
                return@launch
            }

            tempList.forEach { item ->

                Log.d("DELETE_CHECK", "ID = ${item.id}")
                Log.d("DELETE_ONE", "REQUEST DELETE ID=${item.id}")
                Log.d("DELETE_ONE", "MESSAGE=${item.message}")

                try {
                    val response = RetrofitClient.api.deleteLog(item.id)

                    Log.d("DELETE_ONE", "RESPONSE CODE=${response.code()}")
                    Log.d("DELETE_ONE", "RESPONSE BODY=${response.body()?.string()}")

                    if (response.isSuccessful) {
                        Log.d("DELETE_ONE", "SUCCESS DELETE ID=${item.id}")
                    } else {
                        Log.e("DELETE_ONE", "FAILED DELETE ID=${item.id} CODE=${response.code()}")
                    }

                } catch (e: Exception) {
                    Log.e("DELETE_ONE", "EXCEPTION ID=${item.id} MSG=${e.message}")
                }
            }

            warningList.clear()
            Log.d("DELETE_ALL", "UI CLEARED")
        }
    }

    // =========================
    // LOAD
    // =========================
    fun loadLogs() {
        viewModelScope.launch {
            try {
                val logs = RetrofitClient.api.getLogs()

                warningList.clear()
                warningList.addAll(logs.sortedByDescending { it.time })

            } catch (e: Exception) {
                Log.e("API", "Load error: ${e.message}")
            }
        }
    }

    fun toggleSelection(item: WarningItem) {
        selectedItems = if (selectedItems.contains(item.id)) {
            selectedItems - item.id
        } else {
            selectedItems + item.id
        }
    }

    fun updateFromSocket(sensor: Sensor, context: Context) {
        currentAmbang?.let {
            if (currentMode == "Otomatis") {

                checkWarning(
                    context,
                    sensor,
                    it,
                    currentMode
                )

            } else {

                isManualWarningActive = false
                manualWarningMessage = ""

                isAutoWarningActive = false
                autoWarningMessage = ""
            }
        }
    }

    fun restoreDeleted(items: List<WarningItem>) {
        warningList.addAll(0, items)
    }

    fun deleteSelected() {
        viewModelScope.launch {
            val idsToDelete = selectedItems.toList()

            idsToDelete.forEach { id ->

                try {
                    val response = RetrofitClient.api.deleteLog(id)

                    Log.d("DELETE_DEBUG", "Response code: ${response.code()}")
                    Log.d("DELETE_DEBUG", "Body: ${response.body()?.string()}")

                    Log.d("DELETE", "Deleted ID=$id response=$response")

                    if (response.isSuccessful) {
                        warningList.removeAll { it.id == id }
                    } else {
                        Log.e("DELETE", "Gagal delete ID=$id code=${response.code()}")
                    }

                } catch (e: Exception) {
                    Log.e("DELETE", "Error delete ID=$id : ${e.message}")
                }
            }

            selectedItems = emptySet()
        }
    }

    private fun sendLogToServer(
        messages: List<String>,
        sensor: Sensor,
        ambang: AmbangBatas
    ) {
        viewModelScope.launch {
            try {
                messages.forEach { msg ->

                    val (nilai, min, max) = when {
                        msg.contains("Tanah") ->
                            Triple(sensor.kelembaban_tanah, ambang.min_tanah, ambang.max_tanah)

                        msg.contains("Udara") ->
                            Triple(sensor.kelembaban_udara, ambang.min_udara, ambang.max_udara)

                        else ->
                            Triple(sensor.suhu_udara, ambang.min_suhu, ambang.max_suhu)
                    }

                    RetrofitClient.api.saveLog(
                        jenis = "warning",
                        kategori = "sensor",
                        pesan = msg,
                        level = "HIGH",
                        nilai = nilai.toString(),
                        min = min.toString(),
                        max = max.toString()
                    )

                    loadLogs()
                }
            } catch (e: Exception) {
                Log.e("LOG_API", "Gagal kirim log: ${e.message}")
            }
        }
    }
}

class PumpViewModel : ViewModel() {

    var pumpStatus by mutableStateOf("")
        private set

    var isLoading by mutableStateOf(false) // 🔥 PINDAH KE SINI
        private set

    fun setPump(status: String, mode: String) {
        viewModelScope.launch {
            isLoading = true

            try {
                val response = RetrofitClient.api.setPump(
                    status,
                    mode
                )

                if (response.isSuccessful) {
                    val body = response.body()
                    if (body?.status == "success") {
                        pumpStatus = status
                    }
                }

            } catch (e: Exception) {
                e.printStackTrace()
            }

            isLoading = false
        }
    }
}

class MainViewModel : ViewModel() {

    fun updatePumpStatus(status: String) {
        _pumpStatus.value = status
    }

    private var mqtt: MqttManager? = null

    fun initMQTT(context: Context) {

        if (mqtt != null) return

        mqtt = MqttManager(context)

        mqtt?.connect(

            onMessage = { topic, message ->

                if (topic == "smartplant/riwayat") {

                    Log.d("AUTO_RIWAYAT", message)

                    onAutoPump(context, message)
                }
            }
        )
    }


    private var lastAlertType: String? = null

    private fun safeAlert(type: String, title: String, message: String) {

        Log.d("ALERT_FLOW", "SAFE ALERT CHECK → type=$type | last=$lastAlertType")

        if (lastAlertType == type) {
            Log.d("ALERT_FLOW", "BLOCKED (duplicate type)")
            return
        }  // 🔥 STOP SPAM

        lastAlertType = type

        Log.d("ALERT_FLOW", "ALLOWED → sending alert")

        triggerAlert(title, message)
    }

    private val _alertEvent = MutableSharedFlow<AlertEvent>()
    val alertEvent = _alertEvent.asSharedFlow()

    fun triggerAlert(title: String, message: String) {

        Log.d("ALERT_FLOW", "TRIGGER CALLED → title=$title | message=$message | time=${System.currentTimeMillis()}")


        viewModelScope.launch {
            _alertEvent.emit(AlertEvent(title, message))
        }
    }

    private val _autoStatus = mutableStateOf("Sistem otomatis aktif")
    val autoStatus: String get() = _autoStatus.value

    fun setAutoStatus(value: String) {
        _autoStatus.value = value
    }

    // ================= STATE =================
    private val _pumpStatus = mutableStateOf("OFF")
    val pumpStatus: String get() = _pumpStatus.value

    private val _mode = mutableStateOf("Manual")
    val mode: String get() = _mode.value

    private val _isLoading = mutableStateOf(false)
    val isLoading: Boolean get() = _isLoading.value

    private val _avgKT = mutableStateOf(0f)
    val avgKT: Float get() = _avgKT.value

    private val _avgKU = mutableStateOf(0f)
    val avgKU: Float get() = _avgKU.value

    private val _avgSU = mutableStateOf(0f)
    val avgSU: Float get() = _avgSU.value

    private val _avgIH = mutableStateOf(0f)
    val avgIH: Float get() = _avgIH.value


    private val _riwayatList = mutableStateListOf<RiwayatItem>()
    val riwayatList: List<RiwayatItem> = _riwayatList

    private var isSuhuNormal = true

    private fun Float.inRange(min: Int, max: Int): Boolean {
        return this in min.toFloat()..max.toFloat()
    }

    private var lastWateringTime = 0L

    fun updateAverageSensor(
        kt: Float,
        ku: Float,
        su: Float,
        ih: Float
    ) {
        _avgKT.value = kt
        _avgKU.value = ku
        _avgSU.value = su
        _avgIH.value = ih
    }

    fun loadAverageSensor(context: Context) {

        val url =
            "http://kopikaosmartsystem.my.id/get_rata_rata_sensor.php"

        val request = StringRequest(
            Request.Method.GET,
            url,
            { response ->

                try {

                    val json = JSONObject(response)

                    updateAverageSensor(
                        json.getDouble("rata_tanah").toFloat(),
                        json.getDouble("rata_udara").toFloat(),
                        json.getDouble("rata_suhu").toFloat(),
                        json.getDouble("rata_hujan").toFloat()
                    )

                } catch (e: Exception) {
                    Log.e("AVG_SENSOR", e.toString())
                }

            },
            { error ->
                Log.e("AVG_SENSOR", error.toString())
            }
        )

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

    fun setMode(newMode: String) {
        _mode.value = newMode
    }

    fun deleteRiwayat(item: RiwayatItem) {
        _riwayatList.remove(item)
    }

    fun deleteRiwayat(context: Context, item: RiwayatItem) {

        val url = "http://kopikaosmartsystem.my.id/delete_riwayat.php"

        val request = object : StringRequest(
            Method.POST,
            url,
            { response ->

                loadRiwayat(context)

                Toast.makeText(
                    context,
                    "Riwayat berhasil dihapus",
                    Toast.LENGTH_SHORT
                ).show()
            },
            { error ->
                Log.e("DELETE", error.toString())
            }
        ) {

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

                return hashMapOf(
                    "id" to item.id.toString()
                )
            }
        }

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


    fun saveToLocal(context: Context, list: List<RiwayatItem>) {

        val db = DatabaseInstance.get(context)
        val dao = db.riwayatDao()

        viewModelScope.launch {

            dao.clear()

            dao.insertAll(
                list.map {
                    RiwayatEntity(
                        waktu = it.waktu,
                        aksi = it.aksi,
                        keterangan = it.keterangan,
                        jeda = it.jeda,
                        status = it.status,
                        mode = it.mode
                    )
                }
            )
        }
    }


    // ================= CONTROL POMPA =================
    fun onPumpChange(context: Context, status: String, mode: String) {

        Log.d("PUMP_STATUS", status)

        _isLoading.value = true
        _pumpStatus.value = status

        val aksi = if (status == "ON") "Pompa Dinyalakan" else "Pompa Dimatikan"
        val stat = if (status == "ON") "Berjalan" else "Selesai"

        // tampil langsung di UI (optimistic update)
        tambahRiwayat(stat, aksi, mode)

        mqtt?.publish(
            "smartplant/manualPump",
            status
        )

        // kirim ke server
        kirimRiwayatKeServer(context, aksi, stat, mode)

        saveToLocal(context, _riwayatList)

        viewModelScope.launch {
            delay(1000)
            _isLoading.value = false
        }
    }


    // ================= TAMBAH RIWAYAT LOKAL =================
    private fun tambahRiwayat(status: String, aksi: String, mode: String) {

        _riwayatList.add(
            0,
            RiwayatItem(
                id = 0,
                waktu = "Loading...",
                aksi = aksi,
                keterangan = mode,
                jeda = 0,
                status = status,
                mode = mode
            )
        )

        // batasi list
        if (_riwayatList.size > 20) {
            _riwayatList.removeLast()
        }
    }

    // ================= AUTO PUMP =================
    fun onAutoPump(
        context: Context,
        type: String
    ) {

        val aksi = when (type) {

            "JADWAL" -> "Penyiraman Otomatis"

            "KRITIS" -> "Penyiraman Darurat"

            else -> "Penyiraman Otomatis"
        }

        val status = "Berjalan"

        // Tambahkan langsung ke UI
        tambahRiwayat(
            status = status,
            aksi = aksi,
            mode = "Otomatis"
        )

        // Simpan ke server
        kirimRiwayatKeServer(
            context = context,
            aksi = aksi,
            status = status,
            mode = "Otomatis"
        )

        // Simpan ke database lokal
        saveToLocal(context, _riwayatList)
    }

    // ================= API: SIMPAN =================
    private fun kirimRiwayatKeServer(context: Context, aksi: String, status: String, mode: String) {

        val url = "http://kopikaosmartsystem.my.id/save_riwayat.php"

        val request = object : StringRequest(
            Method.POST,
            url,
            { response ->
                Log.d("API", response)

                // reload dari DB biar sinkron
                loadRiwayat(context)
            },
            { error ->
                Log.e("API", error.toString())

                _riwayatList.add(
                    0,
                    RiwayatItem(
                        id = 0,
                        waktu = "Gagal",
                        aksi = aksi,
                        keterangan = "Server Error",
                        jeda = 0,
                        status = "Error",
                        mode = mode
                    )
                )
            }
        ) {
            override fun getParams(): MutableMap<String, String> {
                return hashMapOf(
                    "aksi" to aksi,
                    "status" to status,
                    "keterangan" to mode,
                    "mode" to mode
                )
            }
        }

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


    // ================= API: LOAD =================
    fun loadRiwayat(context: Context) {

        val url = "http://kopikaosmartsystem.my.id/get_riwayat.php"

        val request = StringRequest(
            Request.Method.GET,
            url,
            { response ->

                try {

                    val jsonObject = org.json.JSONObject(response)

                    val jsonArray = jsonObject.getJSONArray("data")

                    val tempList = mutableListOf<RiwayatItem>()

                    for (i in 0 until jsonArray.length()) {

                        val obj = jsonArray.getJSONObject(i)

                        tempList.add(
                            RiwayatItem(
                                id = obj.getInt("id"),
                                waktu = obj.getString("waktu"),
                                aksi = obj.getString("aksi"),
                                keterangan = obj.getString("keterangan"),
                                jeda = 0,
                                status = obj.getString("status"),
                                mode = obj.getString("mode")
                            )
                        )
                    }

                    _riwayatList.clear()
                    _riwayatList.addAll(tempList)

                    saveToLocal(context, tempList)

                } catch (e: Exception) {

                    Log.e("JSON_ERROR", e.message.toString())
                }
            },
            { error ->

                Log.e("API", error.toString())
            }
        )

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

    // data riwayat hari ini, minggu ini, bulan ini

    fun getDataHarian(data: List<RiwayatItem>): List<Pair<String, Int>> {

        val sdf = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())

        val hariMap = mutableMapOf(
            "Sen" to 0,
            "Sel" to 0,
            "Rab" to 0,
            "Kam" to 0,
            "Jum" to 0,
            "Sab" to 0,
            "Min" to 0
        )

        data.forEach {

            val split = it.waktu.split(" ")
            val tanggal = split.getOrNull(0) ?: return@forEach

            val date = sdf.parse(tanggal) ?: return@forEach

            val calData = Calendar.getInstance()
            val calNow = Calendar.getInstance()

            calData.time = date

            if (calData.get(Calendar.WEEK_OF_YEAR) ==
                calNow.get(Calendar.WEEK_OF_YEAR) &&
                calData.get(Calendar.YEAR) ==
                calNow.get(Calendar.YEAR)
            ) {

                val hari = when (calData.get(Calendar.DAY_OF_WEEK)) {
                    Calendar.MONDAY -> "Sen"
                    Calendar.TUESDAY -> "Sel"
                    Calendar.WEDNESDAY -> "Rab"
                    Calendar.THURSDAY -> "Kam"
                    Calendar.FRIDAY -> "Jum"
                    Calendar.SATURDAY -> "Sab"
                    Calendar.SUNDAY -> "Min"
                    else -> ""
                }

                hariMap[hari] = hariMap[hari]!! + 1
            }
        }

        return hariMap.toList()
    }

    fun getDataMingguan(data: List<RiwayatItem>): List<Pair<String, Int>> {

        val sdf = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())

        val mingguMap = mutableMapOf<Int, Int>()

        data.forEach {

            val split = it.waktu.split(" ")
            val tanggal = split.getOrNull(0) ?: return@forEach

            val date = sdf.parse(tanggal) ?: return@forEach

            val calData = Calendar.getInstance()
            val calNow = Calendar.getInstance()

            calData.time = date

            if (calData.get(Calendar.MONTH) ==
                calNow.get(Calendar.MONTH) &&
                calData.get(Calendar.YEAR) ==
                calNow.get(Calendar.YEAR)
            ) {

                val mingguKe = calData.get(Calendar.WEEK_OF_MONTH)

                mingguMap[mingguKe] = (mingguMap[mingguKe] ?: 0) + 1
            }
        }

        for (i in 1..5) {
            mingguMap.putIfAbsent(i, 0)
        }

        return mingguMap
            .toSortedMap()
            .map { "M${it.key}" to it.value }
    }

    fun setLocale(context: Context, languageCode: String) {

        val locale = Locale(languageCode)

        Locale.setDefault(locale)

        val config = context.resources.configuration

        config.setLocale(locale)

        context.resources.updateConfiguration(
            config,
            context.resources.displayMetrics
        )

        (context as Activity).recreate()
    }
}
