package com.pixelized.desktop.lwa.ui.screen.admin.alteration.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.alteration.Alteration
import com.pixelized.shared.lwa.model.tag.Tag
import java.text.Collator

class GMAlterationFactory(
    private val tagFactory: GMTagFactory,
) {

    fun filterAlteration(
        alterations: Collection<Alteration>,
        unAccentFilter: String,
        selectedTagId: String?,
    ): List<Alteration> {
        return alterations.filter {
            val matchName = it.metadata.name.unAccent().contains(
                other = unAccentFilter,
                ignoreCase = true
            )
            val matchTag = selectedTagId == null || it.tags.contains(
                element = selectedTagId
            )
            matchName && matchTag
        }
    }

    fun convertToGMAlterationUio(
        alterations: List<Alteration>,
        tags: Map<String, Tag>,
        selectedTagId: String?,
    ): List<GMAlterationUio> {
        return alterations
            .map { alteration ->
                GMAlterationUio(
                    alterationId = alteration.id,
                    label = alteration.metadata.name,
                    tags = alteration.tags.mapNotNull {
                        tags[it]?.let { tag ->
                            tagFactory.convertToGMTagItemUio(
                                tag = tag,
                                selectedTagId = selectedTagId,
                            )
                        }
                    }
                )
            }
            .sortedWith(compareBy(Collator.getInstance()) { it.label })
    }
}