package com.isidroid.network.ext

import android.content.Context
import com.isidroid.network.QUERY_MOCK_CODE
import com.isidroid.network.QUERY_MOCK_PARAM
import com.isidroid.utils.assetsFileContent
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.Protocol
import okhttp3.Request
import okhttp3.Response
import okhttp3.ResponseBody.Companion.toResponseBody


fun createMockResponse(context: Context, request: Request): Response {
    val uri = request.url.encodedPath.let { url ->
        val delimiter = "v2/"

        url.substring(url.indexOf("v2/"), url.length)
            .replace(delimiter, "")
            .replace("/", ".")
    }

    val mockTag = request.url.queryParameter(QUERY_MOCK_PARAM)
    val mockCode = request.url.queryParameter(QUERY_MOCK_CODE)?.toIntOrNull() ?: 200


    val fileName = buildString {
        append(uri)
        if (!mockTag.isNullOrEmpty())
            append(".$mockTag")

        append(".json")
    }

    val jsonResponse = fileName.assetsFileContent(context)

    return Response.Builder()
        .code(mockCode)
        .message(jsonResponse)
        .request(request)
        .protocol(Protocol.HTTP_1_0)
        .body(jsonResponse.toResponseBody("application/json".toMediaType()))
        .build()
}