package me.eternal.purrfectsnap.mapper.impl

import me.eternal.purrfectsnap.mapper.AbstractClassMapper
import me.eternal.purrfectsnap.mapper.ext.findConstString
import me.eternal.purrfectsnap.mapper.ext.getClassName


class FriendsFeedEventDispatcherMapper : AbstractClassMapper("FriendsFeedEventDispatcher") {
    val classReference = classReference("class")
    val viewModelField = string("viewModelField")

    init {
        mapper {
            classes.asSequence().firstOrNull { clazz ->
                if (clazz.methods.count { it.name == "onClickFeed" || it.name == "onItemLongPress" } != 2) {
                    return@firstOrNull false
                }
                val onItemLongPress = clazz.methods.first { it.name == "onItemLongPress" }
                val viewHolderContainerClass = getClass(onItemLongPress.parameterTypes[0]) ?: return@firstOrNull false

                val viewModelDexField = viewHolderContainerClass.fields.firstOrNull { field ->
                    val typeClass = getClass(field.type) ?: return@firstOrNull false
                    typeClass.methods.firstOrNull {it.name == "toString"}?.implementation?.findConstString("FriendFeedItemViewModel", contains = true) == true
                }?.name ?: return@firstOrNull false

                classReference.set(clazz.getClassName())
                viewModelField.set(viewModelDexField)
                true
            }
        }
    }
}
