package io.nexilis.service.core

import android.net.Uri
import android.os.Build
import android.util.Log
import android.webkit.MimeTypeMap
import androidx.core.net.toUri
import io.nexilis.service.tag
import okhttp3.Call
import okhttp3.Callback
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.asRequestBody
import okhttp3.Response
import java.io.File
import java.io.IOException
import java.nio.file.Files
import java.util.Locale


class Network {

    fun upload(url: String, file: File, completion: (Boolean) -> Unit) {
        val client = OkHttpClient()
        val body: RequestBody = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart(
                    "file", file.name,
                    file.asRequestBody(Files.probeContentType(file.toPath()).toMediaTypeOrNull())
                )
                .addFormDataPart("other_field", "other_field_value")
                .build()
        } else {
            file.toUri()
            MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart(
                    "file", file.name,
                    file.asRequestBody(getMimeType(file.toUri()).toMediaTypeOrNull())
                )
                .addFormDataPart("other_field", "other_field_value")
                .build()
        }
        val request: Request = Request.Builder()
            .url(url)
            .addHeader("User-Agent", "Mozilla/5.0")
            .addHeader("Cookie", "PHPSESSID=123;MOBILE=123")
            .post(body)
            .build()
        Log.d(tag, "Upload:enqueue:$url:${file.name}")
        client.newCall(request).enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                Log.d(tag, "Upload:onFailure")
                completion(false)
            }

            override fun onResponse(call: Call, response: Response) {
                Log.d(tag, "Upload:onResponse:${response.code}")
                completion(response.code == 200)
            }
        })
    }

    private fun getMimeType(uri: Uri): String {
        val fileExtension = MimeTypeMap.getFileExtensionFromUrl(uri.toString())
        MimeTypeMap.getSingleton().getMimeTypeFromExtension(
            fileExtension.lowercase(Locale.getDefault())
        )?.let {
            return it
        }
        return "text/plain"
    }
}