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 SalixInterceptor(private val context: Context, private val listener: InteceptorListener?) :
    Interceptor {

    @Throws(IOException::class)
    override fun intercept(chain: Interceptor.Chain): Response {

        var request = chain.request()
        //sergio: condición para que añada o no headers según se vaya quitando de las llamadas
        //no quitar condición hasta que estén quitados
        if (request.headers().toString().isEmpty()) {
            val newRequest =
                request.newBuilder().addHeader("Content-Type", "application/json").addHeader(
                        "Authorization",
                        (context as MobileApplication).dataStoreApp.readDataStoreKey<String>(TOKEN)
                    ).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
        }
    }
}
