package com.example.modifier.service

import android.accessibilityservice.AccessibilityService
import android.util.Log
import android.view.accessibility.AccessibilityNodeInfo
import com.example.modifier.TraverseResult
import com.example.modifier.baseTag
import com.example.modifier.enums.RcsConnectionStatus
import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking
import java.util.Optional

class ScreenInspector(val context: AccessibilityService) {

    companion object {
        private const val TAG = "$baseTag/Inspector"
    }

    private fun traverse(
        node: AccessibilityNodeInfo?,
        result: TraverseResult,
        log: Boolean = false
    ) {
        if (node == null) {
            return
        }
        val packageInfo = context.packageManager.getPackageInfo(
            node.packageName.toString(), 0
        )
        val className = node.className?.toString()
        val name = node.viewIdResourceName
        val text = node.text?.toString() ?: ""
        val id = node.viewIdResourceName
        val desc = node.contentDescription?.toString() ?: ""

        if (log) {
            Log.d(
                TAG,
                "Node: class=$className, text=$text, desc=$desc, name=$name, id=$id, checkable=${node.isCheckable}, checked=${node.isChecked}, clickable=${node.isClickable}"
            )
        }

        if ("Compose:Draft:Send" == name) {
            result.sendBtn = node
        }

        if ("com.google.android.apps.messaging:id/send_message_button_icon" == id) {
            result.sendBtn = node
        }

        if (text.contains("RCS 聊天") || text.contains("RCS chat")) {
            result.isRcsCapable = true
        }

        if ("com.google.android.apps.messaging:id/tombstone_message" == id &&
            (text.contains("聊天") || text.contains("Chatting with"))
        ) {
            result.isRcsCapable = true
        }

        if ("com.google.android.apps.messaging:id/compose_message_text" == id &&
            (text.contains("RCS 消息") || text.contains("RCS message"))
        ) {
            result.isRcsCapable = true
        }

        if (text.contains("Turn on RCS chats")
            || text.contains("开启 RCS 聊天功能")
            || text.contains("Enable chat features")
            || text.contains("启用聊天功能")
        ) {
            fun findSwitch(node: AccessibilityNodeInfo): Boolean {
                if ("com.google.android.apps.messaging:id/switchWidget" == node.viewIdResourceName) {
                    result.rcsSwitch = node
                    return true
                }
                for (i in 0 until node.childCount) {
                    val child = node.getChild(i)
                    if (findSwitch(child)) {
                        return true
                    }
                }
                return false
            }
            findSwitch(node.parent.parent)
        }

        if ("com.google.android.apps.messaging:id/rcs_sim_status_status_text" == id) {
            if (text.lowercase().contains("connected") || text.lowercase().contains("已连接")) {
                result.rcsConnectionStatus = RcsConnectionStatus.CONNECTED
            }
        }

        if ("android:id/title" == id) {
            when (text) {
                "状态：已连接" -> result.rcsConnectionStatus = RcsConnectionStatus.CONNECTED
                "Status: Connected" -> result.rcsConnectionStatus = RcsConnectionStatus.CONNECTED
            }
        }

        if (desc.contains("Send message") || desc.contains("发送信息")) {
            result.isRcsCapable = true
        }

        if (text.contains("end-to-end encrypted")
            || desc.contains("Send encrypted message")
            || desc.contains("Send end-to-end encrypted message")
            || text.contains("已经过端到端加密")
            || desc.contains("发送加密信息")
            || desc.contains("以端到端加密的方式发送信息")
        ) {
            result.isRcsCapable = true
            result.encrypted = true
        }

        if ("com.google.android.apps.messaging:id/conversation_list_google_tos_popup_positive_button" == id) {
            result.tosAgreeBtn = node
        }

        if ("Turn Off" == text || "关闭" == text) {
            result.closeBtn = node
        }

        if("com.google.android.apps.messaging:id/compose_message_text" == id) {
            result.inputField = node
        }

        if (node.childCount != 0) {
            for (i in 0 until node.childCount) {
                traverse(node.getChild(i), result, log)
            }
        }
    }

    fun traverseNode(result: TraverseResult, log: Boolean = false) {
        runBlocking a@{
            repeat(10) {
                if (context.rootInActiveWindow == null) {
                    Log.i(TAG, "traverseNode: rootInActiveWindow is null")
                    delay(1000)
                } else {
                    return@a
                }
            }
        }
        if (context.rootInActiveWindow == null) {
            Log.e(TAG, "traverseNode: rootInActiveWindow is still null")
            return
        }
        context.getRootInActiveWindow()
        traverse(context.rootInActiveWindow, result, log)
    }
}