package de.sebse.fuplanner2.network

import android.content.Context
import android.os.Build
import com.android.volley.Request
import com.android.volley.RequestQueue
import com.android.volley.Response
import com.android.volley.toolbox.HttpResponse
import com.android.volley.toolbox.HttpStack
import com.android.volley.toolbox.HurlStack
import com.android.volley.toolbox.Volley
import de.sebse.fuplanner2.utils.console
import kotlinx.coroutines.suspendCancellableCoroutine
import java.io.IOException
import java.net.HttpURLConnection
import java.net.URL
import java.security.AccessController.getContext
import java.security.KeyManagementException
import java.security.NoSuchAlgorithmException
import kotlin.coroutines.resume


class Requester(ctx: Context) {
    private var requestQueue: RequestQueue = Volley.newRequestQueue(ctx, object : HurlStack() {
        @Throws(IOException::class)
        override fun createConnection(url: URL?): HttpURLConnection {
            val connection: HttpURLConnection = super.createConnection(url)
            connection.instanceFollowRedirects = false
            return connection
        }
    })

    suspend fun get(url: String, cookies: Map<String, String>?): NetData {
        return suspendCancellableCoroutine { cont ->
            val request = CustomRequest(Request.Method.GET, url, cookies,
                { response -> cont.resume(response) },
                { error -> cont.cancel(error) })
            requestQueue.add(request)
        }
    }

    suspend fun head(url: String, cookies: Map<String, String>?): NetData {
        return suspendCancellableCoroutine { cont ->
            val request = CustomRequest(Request.Method.HEAD, url, cookies,
                { response -> cont.resume(response) },
                { error -> cont.cancel(error) })
            requestQueue.add(request)
        }
    }

    suspend fun post(url: String, cookies: Map<String, String>?, data: Map<String, String>?): NetData {
        return suspendCancellableCoroutine { cont ->
            val request = CustomRequest(Request.Method.POST, url, cookies, data,
                { response -> cont.resume(response) },
                { error -> cont.cancel(error) })
            requestQueue.add(request)
        }
    }
}