package theorycrafter.utils

import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.asExecutor
import okhttp3.Dispatcher
import okhttp3.OkHttpClient
import java.util.concurrent.AbstractExecutorService
import java.util.concurrent.Executor
import java.util.concurrent.TimeUnit


/**
 * Returns an OkHTTP [Dispatcher] dispatching on the given [CoroutineDispatcher].
 */
fun CoroutineDispatcher.asOkHttpDispatcher(): Dispatcher {
    return Dispatcher(
        object: Executor by this.asExecutor(), AbstractExecutorService() {

            override fun shutdown() {
                error("CoroutineDispatcher can't be shut down")
            }

            override fun shutdownNow(): MutableList<Runnable> {
                error("CoroutineDispatcher can't be shut down")
            }

            override fun isShutdown(): Boolean {
                return false
            }

            override fun isTerminated(): Boolean {
                return false
            }

            override fun awaitTermination(timeout: Long, unit: TimeUnit): Boolean {
                Thread.sleep(unit.toMillis(timeout))
                return false
            }

        }
    )
}


/**
 * Adds an interceptor that sets the given header.
 */
fun OkHttpClient.Builder.setHeader(name: String, value: String): OkHttpClient.Builder =
    addInterceptor { chain ->
        chain.proceed(
            chain.request().newBuilder()
                .header(name, value)
                .build()
        )
    }
