/*
 * Copyright 2019 New Vector Ltd
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package im.vector.matrix.android.internal.crypto.tasks

import im.vector.matrix.android.api.session.crypto.CryptoService
import im.vector.matrix.android.api.session.events.model.Event
import im.vector.matrix.android.api.session.room.send.SendState
import im.vector.matrix.android.internal.crypto.model.MXEncryptEventContentResult
import im.vector.matrix.android.internal.session.room.send.LocalEchoUpdater
import im.vector.matrix.android.internal.task.Task
import im.vector.matrix.android.internal.util.awaitCallback
import javax.inject.Inject

internal interface EncryptEventTask : Task<EncryptEventTask.Params, Event> {
    data class Params(val roomId: String,
                      val event: Event,
                      /**Do not encrypt these keys, keep them as is in encrypted content (e.g. m.relates_to)*/
                      val keepKeys: List<String>? = null,
                      val crypto: CryptoService
    )
}

internal class DefaultEncryptEventTask @Inject constructor(
//        private val crypto: CryptoService
        private val localEchoUpdater: LocalEchoUpdater
) : EncryptEventTask {
    override suspend fun execute(params: EncryptEventTask.Params): Event {
        if (!params.crypto.isRoomEncrypted(params.roomId)) return params.event
        val localEvent = params.event
        if (localEvent.eventId == null) {
            throw IllegalArgumentException()
        }

        localEchoUpdater.updateSendState(localEvent.eventId, SendState.ENCRYPTING)

        val localMutableContent = localEvent.content?.toMutableMap() ?: mutableMapOf()
        params.keepKeys?.forEach {
            localMutableContent.remove(it)
        }

//        try {
        awaitCallback<MXEncryptEventContentResult> {
            params.crypto.encryptEventContent(localMutableContent, localEvent.type, params.roomId, it)
        }.let { result ->
            val modifiedContent = HashMap(result.eventContent)
            params.keepKeys?.forEach { toKeep ->
                localEvent.content?.get(toKeep)?.let {
                    // put it back in the encrypted thing
                    modifiedContent[toKeep] = it
                }
            }
            val safeResult = result.copy(eventContent = modifiedContent)
            return localEvent.copy(
                    type = safeResult.eventType,
                    content = safeResult.eventContent
            )
        }
//        } catch (throwable: Throwable) {
//            val sendState = when (throwable) {
//                is Failure.CryptoError -> SendState.FAILED_UNKNOWN_DEVICES
//                else                   -> SendState.UNDELIVERED
//            }
//            localEchoUpdater.updateSendState(localEvent.eventId, sendState)
//            throw throwable
//        }
    }
}
