package com.fusi24.entryPermitScanner.data.interceptor;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.widget.Toast;

import com.fusi24.entryPermitScanner.data.entity.APIError;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import timber.log.Timber;

public class RestHeaderModifierInterceptor implements Interceptor {

    private String token;
    private String userId;
    private Context context;

    public RestHeaderModifierInterceptor(String token, String userId, Context context){
        this.token = token;
        this.userId = userId;
        this.context = context;
    }

    @NotNull
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request()
                .newBuilder()
                .addHeader("Content-Type", "application/json")
                .addHeader("x-api-key", token)
                .addHeader("userId",userId)
                .build();
        Response response = chain.proceed(request);

        if(!response.isSuccessful()){
            APIError error = new APIError(response.code(),response.message(),response.header("refNumber"));
            Timber.d("DEVELOPER : %s", error);
            if(error.getRefNumber() != null)
                backgroundThreadToast(context,"Error Rest API Service with Ref Number: "+error.getRefNumber());
            else
                backgroundThreadToast(context,"Error Occurred with Response: "+error.getStatusCode()+" "+error.getMessage());
        }

        return response;
    }

    public static void backgroundThreadToast(final Context context, final String msg){
        if(context != null && msg != null){
            new Handler(Looper.getMainLooper()).post(() -> Toast.makeText(context, msg, Toast.LENGTH_LONG).show());
        }
    }
}
