package app.furmeet.events.system.helper

import android.webkit.WebResourceResponse
import java.io.BufferedInputStream
import java.io.InputStream
import java.net.HttpURLConnection
import java.net.URL

class Download(val url: String) {
    val urlurl = URL(url)
    val httpClient: HttpURLConnection = urlurl.openConnection() as HttpURLConnection
    val bufferedInputStream = BufferedInputStream(httpClient.inputStream)

    val mimeType: String
        get() = httpClient.contentType

    val encoding: String
        get() = httpClient.contentEncoding

    val httpStatus: Int
        get() = httpClient.responseCode

    val success: Boolean
        get() = httpStatus == HttpURLConnection.HTTP_OK

    val cookies: MutableMap<String, String>
        get() = httpClient.headerFields.map { it.key to it.value[0] }.toMap().toMutableMap()

    val data: InputStream
        get() = bufferedInputStream

    val webResourceResponse: WebResourceResponse?
        get() {
            if (success) {
                return WebResourceResponse(mimeType, encoding, httpStatus, "memory", cookies, data)
            }
            return null
        }

    val okdata: InputStream
        get() = if (success) data else emptyStream

    val emptyStream = ByteArray(0).inputStream()
}