package com.example.modifier.utils

import android.view.accessibility.AccessibilityNodeInfo

fun AccessibilityNodeInfo?.findFirstByDesc(desc: String): AccessibilityNodeInfo? {
    if (this == null) {
        return null
    }
    if (this.contentDescription?.toString()?.lowercase()?.contains(desc.lowercase()) == true) {
        return this
    }
    for (i in 0 until this.childCount) {
        val child = this.getChild(i)
        val result = child.findFirstByDesc(desc)
        if (result != null) {
            return result
        }
    }
    return null
}

fun AccessibilityNodeInfo?.findFirstByIdAndText(
    id: String,
    vararg text: String
): AccessibilityNodeInfo? {
    if (this == null) {
        return null
    }
    if (this.viewIdResourceName?.toString()?.lowercase()?.contains(id.lowercase()) == true
        && text.any { this.text?.toString()?.lowercase()?.contains(it.lowercase()) == true }
    ) {
        return this
    }
    for (i in 0 until this.childCount) {
        val child = this.getChild(i)
        val result = child.findFirstByIdAndText(id, *text)
        if (result != null) {
            return result
        }
    }
    return null
}

fun AccessibilityNodeInfo.findFirstScrollable(): AccessibilityNodeInfo? {
    if (this.isScrollable) {
        return this
    }
    for (i in 0 until this.childCount) {
        val child = this.getChild(i)
        val result = child.findFirstScrollable()
        if (result != null) {
            return result
        }
    }
    return null
}

fun AccessibilityNodeInfo.findAllScrollable(): List<AccessibilityNodeInfo> {
    val result = mutableListOf<AccessibilityNodeInfo>()
    if (this.isScrollable) {
        result.add(this)
    }
    for (i in 0 until this.childCount) {
        val child = this.getChild(i)
        result.addAll(child.findAllScrollable())
    }
    return result
}

fun AccessibilityNodeInfo.findFirstCheckable(): AccessibilityNodeInfo? {
    if (this.isCheckable) {
        return this
    }
    for (i in 0 until this.childCount) {
        val child = this.getChild(i)
        val result = child.findFirstCheckable()
        if (result != null) {
            return result
        }
    }
    return null
}