package es.verdnatura.domain

import android.content.Context
import android.view.View
import es.verdnatura.MobileApplication
import es.verdnatura.domain.ConstAndValues.TOKEN
import es.verdnatura.presentation.common.InteceptorListener
import okhttp3.Interceptor
import okhttp3.Response
import java.io.IOException

class SilexInterceptor(private val context: Context, private val listener: InteceptorListener?) :
    Interceptor {
    @Throws(IOException::class)
    override fun intercept(chain: Interceptor.Chain): Response {

        var request = chain.request()

        if (request.headers().toString().isEmpty()) {

            val newRequest =
                request.newBuilder().addHeader("aplicacion", "json").addHeader("version", "1")
                    .addHeader(
                        "Authorization",
                        (context as MobileApplication).dataStoreApp.readDataStoreKey<String>(TOKEN)
                    ).addHeader("Content-Type", "application/json")
                    .addHeader("Accept-Language", (context).getLanguage()).build()
            request = newRequest
        }
        if (request.url().toString().contains("renew")) {
            return chain.proceed(request)
        } else {
            listener!!.onInterceptionResult(View.VISIBLE)
            val response = chain.proceed(request)
            listener.onInterceptionResult(View.INVISIBLE)
            return response
        }
    }
}
