package com.isidroid.test_utils

import com.google.gson.GsonBuilder
import okhttp3.OkHttpClient
import okhttp3.mockwebserver.MockWebServer
import org.json.JSONObject
import org.junit.rules.TestRule
import org.junit.runner.Description
import org.junit.runners.model.Statement
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit


private val gson = GsonBuilder()
    .create()

val okHttpClient by lazy {
    OkHttpClient.Builder()
        .connectTimeout(1, TimeUnit.SECONDS)
        .readTimeout(1, TimeUnit.SECONDS)
        .writeTimeout(1, TimeUnit.SECONDS)
        .build()
}

fun <T> createApi(mockWebServer: MockWebServer, cl: Class<T>): T = Retrofit.Builder()
    .baseUrl(mockWebServer.url("/"))
    .client(okHttpClient)
    .addConverterFactory(GsonConverterFactory.create(gson))
    .build()
    .create(cl)


/**
 * The the file in the [filePath] and return its content as a [String]
 */
fun getFileAsString(filePath: String): String {
    return Thread.currentThread().contextClassLoader?.getResourceAsStream(filePath)?.bufferedReader().use { it?.readText() }.orEmpty()
}

fun getMockResponse(fileName: String) = getFileAsString("api-response/$fileName")

class RepeatRule : TestRule {
    private class RepeatStatement(private val statement: Statement, private val repeat: Int) : Statement() {
        @Throws(Throwable::class)
        override fun evaluate() {
            for (i in 0 until repeat) {
                statement.evaluate()
            }
        }
    }

    override fun apply(statement: Statement, description: Description): Statement {
        var result = statement
        val repeat = description.getAnnotation(RepeatTest::class.java)
        if (repeat != null) {
            val times = repeat.value
            result = RepeatStatement(statement, times)
        }
        return result
    }
}

val String?.isMethodPost get() = "post" == this?.lowercase()
val String?.isMethodPut get() = "put" == this?.lowercase()

@Retention(AnnotationRetention.RUNTIME)
@Target(AnnotationTarget.FUNCTION, AnnotationTarget.ANNOTATION_CLASS)
annotation class RepeatTest(val value: Int = 1)