/*
 * Copyright 2023, 2024 New Vector Ltd.
 *
 * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
 * Please see LICENSE files in the repository root for full details.
 */

package io.element.android.features.messages.impl.forward

import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateOf
import dagger.assisted.Assisted
import dagger.assisted.AssistedFactory
import dagger.assisted.AssistedInject
import io.element.android.libraries.architecture.AsyncAction
import io.element.android.libraries.architecture.Presenter
import io.element.android.libraries.architecture.runCatchingUpdatingState
import io.element.android.libraries.matrix.api.core.EventId
import io.element.android.libraries.matrix.api.core.RoomId
import io.element.android.libraries.matrix.api.timeline.TimelineProvider
import io.element.android.libraries.matrix.api.timeline.getActiveTimeline
import kotlinx.collections.immutable.ImmutableList
import kotlinx.collections.immutable.toPersistentList
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch

class ForwardMessagesPresenter @AssistedInject constructor(
    @Assisted eventId: String,
    @Assisted private val timelineProvider: TimelineProvider,
    private val appCoroutineScope: CoroutineScope,
) : Presenter<ForwardMessagesState> {
    private val eventId: EventId = EventId(eventId)

    @AssistedFactory
    interface Factory {
        fun create(eventId: String, timelineProvider: TimelineProvider): ForwardMessagesPresenter
    }

    private val forwardingActionState: MutableState<AsyncAction<List<RoomId>>> = mutableStateOf(AsyncAction.Uninitialized)

    fun onRoomSelected(roomIds: List<RoomId>) {
        appCoroutineScope.forwardEvent(eventId, roomIds.toPersistentList(), forwardingActionState)
    }

    @Composable
    override fun present(): ForwardMessagesState {
        fun handleEvents(event: ForwardMessagesEvents) {
            when (event) {
                ForwardMessagesEvents.ClearError -> forwardingActionState.value = AsyncAction.Uninitialized
            }
        }

        return ForwardMessagesState(
            forwardAction = forwardingActionState.value,
            eventSink = { handleEvents(it) }
        )
    }

    private fun CoroutineScope.forwardEvent(
        eventId: EventId,
        roomIds: ImmutableList<RoomId>,
        isForwardMessagesState: MutableState<AsyncAction<List<RoomId>>>,
    ) = launch {
        suspend {
            timelineProvider.getActiveTimeline().forwardEvent(eventId, roomIds).getOrThrow()
            roomIds
        }.runCatchingUpdatingState(isForwardMessagesState)
    }
}
