package com.pixelized.desktop.lwa.ui.screen.admin.item.list

import com.pixelized.desktop.lwa.ui.screen.admin.common.tag.GMTagFactory
import com.pixelized.desktop.lwa.utils.extention.unAccent
import com.pixelized.shared.lwa.model.item.Item
import com.pixelized.shared.lwa.model.tag.Tag
import java.text.Collator

class GMItemFactory(
    private val tagFactory: GMTagFactory,
) {
    fun filterItem(
        items: Collection<Item>,
        unAccentFilter: String,
        selectedTagId: String?,
    ): List<Item> {
        return items.filter {
            val matchName = it.metadata.label.unAccent().contains(
                other = unAccentFilter,
                ignoreCase = true
            )
            val matchTag = selectedTagId == null || it.tags.contains(
                element = selectedTagId
            )
            matchName && matchTag
        }
    }

    fun convertToGMItemUio(
        items: List<Item>,
        tags: Map<String, Tag>,
        selectedTagId: String?,
    ): List<GMItemUio> {
        return items
            .map { item ->
                GMItemUio(
                    itemId = item.id,
                    label = item.metadata.label,
                    tags = item.tags.mapNotNull {
                        tags[it]?.let { tag ->
                            tagFactory.convertToGMTagItemUio(
                                tag = tag,
                                selectedTagId = selectedTagId,
                            )
                        }
                    }
                )
            }
            .sortedWith(compareBy(Collator.getInstance()) { it.label })
    }
}