package com.doverfuelingsolutions.issp.api.basic

import androidx.core.os.bundleOf
import com.doverfuelingsolutions.issp.DFSApplication
import com.doverfuelingsolutions.issp.R
import com.doverfuelingsolutions.issp.data.GlobalData
import com.doverfuelingsolutions.issp.utils.DFSToastUtil
import com.doverfuelingsolutions.issp.utils.StringUtil
import com.doverfuelingsolutions.issp.utils.log.DFSLog
import com.doverfuelingsolutions.issp.view.LoginActivity
import okhttp3.Interceptor
import okhttp3.Response

class AuthInterceptor : Interceptor {

    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request().newBuilder()
            .addHeader("Content-Type", "application/json")
            .addHeader("Accept", "application/json")
            .addHeader("DeviceSN", GlobalData.serialNumber.get())
        if (GlobalData.accessToken.get().isNotBlank()) request.header("Authorization", "Bearer ${GlobalData.accessToken.get()}")
        if (GlobalData.businessId.get().isNotBlank()) request.header("CurrentBuId", GlobalData.businessId.get())
        val response = chain.proceed(request.build())
        if (response.code() == 401 && response.message().equals("Unauthorized", true)) {
            DFSToastUtil.fail(R.string.login_expire_msg)
            LoginActivity.start(DFSApplication.instance.applicationContext, bundleOf(
                Pair(LoginActivity.autoLogin, false),
                Pair(LoginActivity.loginMessage, StringUtil.get(R.string.login_expire_msg)),
            ))
        }
        return response
    }
}