package dp.kotul.solrapiapplication.facade

import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.node.ObjectNode
import dp.kotul.solrapiapplication.client.SolrClient
import dp.kotul.solrapiapplication.helper.CollectionHelper
import dp.kotul.solrapiapplication.model.templategroup.TemplateGroupDocument
import dp.kotul.solrapiapplication.model.templategroup.UpdateTemplateGroupsRequest
import dp.kotul.solrapiapplication.service.ApiResponseService
import dp.kotul.solrapiapplication.service.UpdateObjectService
import dp.kotul.solrapimodel.solrsearch.AssetType.TEMPLATE_GROUP
import dp.kotul.solrapimodel.solrsearch.SolrUtils
import org.slf4j.Logger
import org.springframework.http.ResponseEntity
import org.springframework.stereotype.Component

interface TemplateGroupFacade {
    fun updateTemplateGroups(updateTemplateGroupRequest: UpdateTemplateGroupsRequest)
}

@Component
class TemplateGroupFacadeImpl(
    val solrClient: SolrClient,
    val collectionHelper: CollectionHelper,
    val updateObjectService: UpdateObjectService,
    val apiResponseService: ApiResponseService,
    val mapper: ObjectMapper,
    val log: Logger
) : TemplateGroupFacade {

    override fun updateTemplateGroups(updateTemplateGroupRequest: UpdateTemplateGroupsRequest) {

        updateTemplateGroupRequest.templateGroups.forEach {
            val uniqueId = SolrUtils.getUniqueSolrDocumentId(it.templateGroupId.toString(), TEMPLATE_GROUP)

            log.info("Updating document for id $uniqueId with request: $it")
            val templateGroupDocument = TemplateGroupDocument(
                id = uniqueId,
                name = it.name,
                templateGroupId = it.templateGroupId,
                templateCount = it.templateCount,
                templateTypes = it.templateTypes,
                modifiedDate = it.modified,
                createdDate = it.created
            )
            val json = updateObjectService.createJsonForUpdate(templateGroupDocument)
            updateForAllLanguages(json, updateTemplateGroupRequest.comId)
        }
    }

    private fun updateForAllLanguages(json: String, laeId: Int): ResponseEntity<JsonNode?> {
        val collection = collectionHelper.getCollection(laeId)

        val objectNode = mapper.readTree(json) as ObjectNode
        val documentId = objectNode.get("id").asText().substringBeforeLast("_")

        objectNode.put("id", "${documentId}_${laeId}")
        objectNode.put("lae_id", laeId)
        val solrResponse = solrClient.update(collection,"[$objectNode]")

        return apiResponseService.getUpdateResponseEntity(solrResponse)
    }
}
