package com.example.modifier

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.liveData
import com.example.modifier.enums.RcsConfigureState
import com.example.modifier.service.ModifierService
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import org.apache.commons.collections4.queue.CircularFifoQueue

class MsgAppModel(private val modifierService: ModifierService) {

    private val rcsConfigureState = MutableLiveData(RcsConfigureState.CONFIGURED)
    private val logcat = liveData(Dispatchers.IO) {
        try {
            val logs = CircularFifoQueue<String>(128)
            val p = Runtime.getRuntime().exec("su")
            p.outputStream.bufferedWriter().use { writer ->
                writer.write("logcat -c")
                writer.newLine()
                writer.flush()
                writer.write("logcat BugleRcsEngine:D *:S -v time")
                writer.newLine()
                writer.flush()
            }
            p.inputStream
                .bufferedReader()
                .useLines { lines ->
                    lines.forEach { line ->
                        if (line.contains("destState=CheckPreconditionsState")) {
                            rcsConfigureState.postValue(RcsConfigureState.NOT_CONFIGURED)
                        } else if (line.contains("destState=ReadyState")) {
                            rcsConfigureState.postValue(RcsConfigureState.READY)
                        } else if (line.contains("destState=WaitingForOtpState")) {
                            rcsConfigureState.postValue(RcsConfigureState.WAITING_FOR_OTP)
                        } else if (line.contains("destState=VerifyOtpState")) {
                            rcsConfigureState.postValue(RcsConfigureState.VERIFYING_OTP)
                        } else if (line.contains("destState=ConfiguredState")) {
                            rcsConfigureState.postValue(RcsConfigureState.CONFIGURED)
                        } else if (line.contains("destState=WaitingForRcsDefaultOnState")) {
                            rcsConfigureState.postValue(RcsConfigureState.WAITING_FOR_DEFAULT_ON)
                        } else if (line.contains("destState=RetryState")) {
                            rcsConfigureState.postValue(RcsConfigureState.RETRY)
                        }
                        Regex("(?<time>\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}.\\d{3}) I/BugleRcsEngine\\(\\W*\\d+\\): (?<log>.*)").matchEntire(
                            line
                        )?.apply {
                            val time = groups["time"]?.value?.dropLast(4)
                            val log = groups["log"]?.value
                                ?.replace(Regex("\\[\\w+-\\w+-\\w+-\\w+-\\w+]"), "")
                                ?.replace(Regex("\\[CONTEXT.*]"), "")
                                ?.trim()

                            if (time != null && log != null) {
                                if (log.contains("destState=")) {
                                    logs.add("$time: $log")
                                    emit(logs.joinToString("\n"))
                                    delay(100)
                                    emit(logs.joinToString("\n"))
                                }
                            }
                        }
                    }
                }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    fun isRcsSwitchOn(): Boolean {
        val nodes = modifierService.getNodes()
        nodes.find {
            it.text.contains("Turn on RCS chats") || it.text.contains("开启 RCS 聊天功能")
        }?.let { node ->
            modifierService.getNodes(node)
                .find { "com.google.android.apps.messaging:id/switchWidget" == it.viewIdResourceName }
                ?.let {
                    return true
                }
        }
        return false
    }
}