package ru.forbion.f7cloud.feature.files

import android.content.Context
import okhttp3.Request
import ru.forbion.f7cloud.core.auth.AuthSession
import ru.forbion.f7cloud.core.auth.OcsUserResolver
import ru.forbion.f7cloud.core.network.NetworkFactory
import ru.forbion.f7cloud.core.network.UnauthorizedException
import ru.forbion.f7cloud.core.network.davFileUrl
import java.io.File

class FileDownloadRepository(private val context: Context) {
    fun download(session: AuthSession, relativePath: String, fileName: String): File {
        val client = NetworkFactory.newAuthedClient(
            session.username,
            session.appPassword,
            session.trustAllCerts,
        )
        val userId = session.davUserId ?: OcsUserResolver.resolveDavUserId(session)
        val url = davFileUrl(session.serverUrl, userId, relativePath)
        val request = Request.Builder()
            .url(url)
            .header("Accept", "*/*")
            .get()
            .build()
        client.newCall(request).execute().use { response ->
            if (!response.isSuccessful || response.body == null) {
                error("Не удалось скачать файл (HTTP ${response.code})")
            }
            val dir = File(context.cacheDir, "f7_files").apply { mkdirs() }
            val safeName = fileName.replace(Regex("[\\\\/:*?\"<>|]"), "_")
            val out = File(dir, safeName)
            response.body!!.byteStream().use { input ->
                out.outputStream().use { output -> input.copyTo(output) }
            }
            return out
        }
    }
}
