/*
 * F7cloud Talk - Android Client
 *
 * SPDX-FileCopyrightText: 2022 Álvaro Brey <alvaro@alvarobrey.com>
 * SPDX-FileCopyrightText: 2022 Nextcloud GmbH
 * SPDX-License-Identifier: GPL-3.0-or-later
 */
package ru.f7cloud.talk.messagesearch

import android.util.Log
import ru.f7cloud.talk.data.user.model.User
import ru.f7cloud.talk.models.domain.SearchMessageEntry
import ru.f7cloud.talk.repositories.unifiedsearch.UnifiedSearchRepository
import ru.f7cloud.talk.repositories.unifiedsearch.UnifiedSearchRepositoryImpl.Companion.PROVIDER_TALK_MESSAGE
import ru.f7cloud.talk.repositories.unifiedsearch.UnifiedSearchRepositoryImpl.Companion.PROVIDER_TALK_MESSAGE_CURRENT
import ru.f7cloud.talk.utils.ApiUtils
import io.reactivex.Observable
import io.reactivex.disposables.Disposable

class MessageSearchHelper @JvmOverloads constructor(
    private val unifiedSearchRepository: UnifiedSearchRepository,
    private val currentUser: User?,
    private val fromRoom: String? = null
) {

    data class MessageSearchResults(val messages: List<SearchMessageEntry>, val hasMore: Boolean)

    private var unifiedSearchDisposable: Disposable? = null
    private var previousSearch: String? = null
    private var previousCursor: Int = 0
    private var previousResults: List<SearchMessageEntry> = emptyList()

    fun startMessageSearch(search: String): Observable<MessageSearchResults> {
        resetCachedData()
        return doSearch(search)
    }

    fun loadMore(): Observable<MessageSearchResults>? {
        previousSearch?.let {
            return doSearch(it, previousCursor)
        }
        return null
    }

    fun cancelSearch() {
        disposeIfPossible()
    }

    private fun doSearch(search: String, cursor: Int = 0): Observable<MessageSearchResults> {
        disposeIfPossible()
        return searchCall(search, cursor)
            .map { results ->
                previousSearch = search
                previousCursor = results.cursor
                previousResults = previousResults + results.entries
                MessageSearchResults(previousResults, results.hasMore)
            }
            .doOnSubscribe {
                unifiedSearchDisposable = it
            }
            .doOnError { throwable ->
                Log.e(TAG, "message search - ERROR", throwable)
                resetCachedData()
                disposeIfPossible()
            }
            .doOnComplete(this::disposeIfPossible)
    }

    private fun searchCall(
        search: String,
        cursor: Int
    ): Observable<UnifiedSearchRepository.UnifiedSearchResults<SearchMessageEntry>> {
        val credentials = ApiUtils.getCredentials(currentUser?.username, currentUser?.token)
        val result = when {
            fromRoom != null -> {
                val url = ApiUtils.getUrlForUnifiedSearch(currentUser?.baseUrl!!, PROVIDER_TALK_MESSAGE_CURRENT)
                unifiedSearchRepository.searchInRoom(
                    credentials,
                    url,
                    roomToken = fromRoom,
                    searchTerm = search,
                    cursor = cursor
                )
            }

            else -> {
                val url = ApiUtils.getUrlForUnifiedSearch(currentUser?.baseUrl!!, PROVIDER_TALK_MESSAGE)
                unifiedSearchRepository.searchMessages(
                    credentials,
                    url,
                    searchTerm = search,
                    cursor = cursor
                )
            }
        }
        return result
    }

    private fun resetCachedData() {
        previousSearch = null
        previousCursor = 0
        previousResults = emptyList()
    }

    private fun disposeIfPossible() {
        unifiedSearchDisposable?.dispose()
        unifiedSearchDisposable = null
    }

    companion object {
        private val TAG = MessageSearchHelper::class.simpleName
    }
}
