package dp.kotul.templategroupsbackend.model.solrsearch.template

import dp.kotul.templategroupsbackend.model.response.TemplateVariableType
import com.fasterxml.jackson.annotation.JsonAlias
import com.fasterxml.jackson.annotation.JsonProperty
import com.fasterxml.jackson.databind.ObjectMapper
import dp.kotul.solrapimodel.solrsearch.TemplateType
import dp.kotul.starter.autoconfig.SpringContext
import java.time.Instant

data class TemplateSolr(
        @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
        val id: String,
        val assetType: String,
        @JsonAlias("templateExtId", "org_id")
        val templateExtId: String,
        @JsonAlias("templateType", "template_type_s")
        val templateType: TemplateType,
        @JsonAlias("name", "title")
        val name: String,
        @JsonAlias("createdDate", "created_date")
        val createdDate: Instant,
        @JsonAlias("thumbnailRef", "thumbnail_ref")
        val thumbnailRef: String,
        @JsonAlias("lowResRef", "lowres_ref")
        val lowResRef: String,
        @JsonAlias("variables", "variables_ss")
        @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
        val variables: List<String> = emptyList(),
        @JsonAlias("metaData", "metadata_s")
        @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
        val metaData: String?
) {
    val type = templateType.value
    val templateVariables = {
        val mapper = SpringContext.getBean(ObjectMapper::class.java)
        variables.map { mapper.readValue(it, TemplateSolrVariable::class.java) }
    }.invoke().filter { TemplateVariableType.getTemplateVariableType(it.templateVariableExtType) != null }
}
