package ru.forbion.f7cloud.feature.files

import ru.forbion.f7cloud.core.auth.AuthSession

class OfficeFileOpener(
    private val richdocumentsRepository: RichdocumentsRepository = RichdocumentsRepository(),
) {
    fun prepareLaunch(session: AuthSession, fileId: Long, title: String): OfficeEditorLaunch {
        val collaboraBaseUrl = OfficeWarmup.getCachedCollaboraUrl(session.serverUrl)
            .ifBlank { richdocumentsRepository.fetchCollaboraPublicUrl(session) }
        val url = richdocumentsRepository.createDirectUrl(session, fileId)
        return OfficeEditorLaunch(
            url = url,
            title = title,
            username = session.username,
            password = session.appPassword,
            trustAllCerts = session.trustAllCerts,
            serverUrl = session.serverUrl,
            collaboraBaseUrl = collaboraBaseUrl,
        )
    }

    fun prepareLaunchFromLink(session: AuthSession, link: String, title: String): OfficeEditorLaunch {
        val fileId = OfficeFileLinks.parseFileId(link, session.serverUrl)
            ?: error("Не удалось определить файл по ссылке")
        return prepareLaunch(session, fileId, OfficeFileLinks.titleFromLink(link, title))
    }
}
