package ch.threema.app.processors.incomingcspmessage.conversation

import ch.threema.app.managers.ServiceManager
import ch.threema.app.processors.incomingcspmessage.IncomingCspMessageSubTask
import ch.threema.app.processors.incomingcspmessage.ReceiveStepsResult
import ch.threema.app.processors.incomingcspmessage.groupcontrol.runCommonGroupReceiveSteps
import ch.threema.app.tasks.runCommonEditMessageReceiveSteps
import ch.threema.base.utils.getThreemaLogger
import ch.threema.data.models.GroupModel
import ch.threema.domain.protocol.csp.messages.GroupEditMessage
import ch.threema.domain.taskmanager.ActiveTaskCodec
import ch.threema.domain.taskmanager.TriggerSource

private val logger = getThreemaLogger("IncomingGroupEditMessageTask")

class IncomingGroupEditMessageTask(
    editMessage: GroupEditMessage,
    triggerSource: TriggerSource,
    serviceManager: ServiceManager,
) : IncomingCspMessageSubTask<GroupEditMessage>(editMessage, triggerSource, serviceManager) {
    private val messageService by lazy { serviceManager.messageService }
    private val groupService by lazy { serviceManager.groupService }
    private val groupModelRepository by lazy { serviceManager.modelRepositories.groups }
    private val identityStore by lazy { serviceManager.identityStore }

    override suspend fun executeMessageStepsFromRemote(handle: ActiveTaskCodec): ReceiveStepsResult {
        logger.debug("IncomingGroupEditMessageTask id: {}", message.data.messageId)

        val groupModel = runCommonGroupReceiveSteps(message, handle, serviceManager)
            ?: return ReceiveStepsResult.DISCARD

        return applyEdit(groupModel)
    }

    override suspend fun executeMessageStepsFromSync(): ReceiveStepsResult {
        logger.debug("IncomingGroupEditMessageTask id: {}", message.data.messageId)

        val groupModel = groupModelRepository.getByCreatorIdentityAndId(
            message.groupCreator,
            message.apiGroupId,
        )

        if (groupModel == null) {
            logger.error("Received a reflected group edit message in an unknown group")
            return ReceiveStepsResult.DISCARD
        }

        return applyEdit(groupModel)
    }

    private fun applyEdit(groupModel: GroupModel): ReceiveStepsResult {
        val myIdentity = identityStore.getIdentityString()
            ?: throw IllegalStateException("Cannot apply edit when no identity is available")

        val receiver = groupService.createReceiver(groupModel) ?: run {
            logger.error("Could not get message receiver")
            return ReceiveStepsResult.DISCARD
        }
        val editedMessage = runCommonEditMessageReceiveSteps(
            myIdentity = myIdentity,
            editMessageSenderIdentity = message.fromIdentity,
            editMessageCreatedAt = message.timestamp,
            messageId = message.data.messageId,
            receiver = receiver,
            messageService = messageService,
        )
            ?: return ReceiveStepsResult.DISCARD

        messageService.saveEditedMessageText(editedMessage, message.data.text, message.timestamp)

        return ReceiveStepsResult.SUCCESS
    }
}
