package com.kbs.kbsintranett;

import android.content.Intent;
import com.kbs.kbsintranett.BuildConfig; // Lagt til import
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import java.io.IOException;
import java.util.List;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class RetrofitClient {
    private static final String BASE_URL = "https://intranet.kbs.no/";
    private static Retrofit retrofit = null;

    public static final String ACTION_AUTH_FAILED = "com.kbs.kbsintranett.AUTH_FAILED";

    public static WordPressApiService getApiService() {
        if (retrofit == null) {

            HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
            if (BuildConfig.DEBUG) {
                logging.setLevel(HttpLoggingInterceptor.Level.BASIC);
            } else {
                logging.setLevel(HttpLoggingInterceptor.Level.NONE);
            }

            OkHttpClient client = new OkHttpClient.Builder()
                    .addInterceptor(logging)
                    .addInterceptor(new Interceptor() {
                        @Override
                        public Response intercept(Chain chain) throws IOException {
                            Request originalRequest = chain.request();
                            Request.Builder builder = originalRequest.newBuilder();

                            String dynamicCookie = UserManager.getInstance().getCookie();
                            if (dynamicCookie != null && !dynamicCookie.isEmpty()) {
                                builder.header("Cookie", dynamicCookie);
                            }

                            return chain.proceed(builder.build());
                        }
                    })
                    .addInterceptor(new Interceptor() {
                        @Override
                        public Response intercept(Chain chain) throws IOException {
                            Request request = chain.request();
                            Response response = chain.proceed(request);

                            if (response.code() == 401 || response.code() == 403) {
                                if (!request.url().toString().contains("kbs/v1/login")) {
                                    Intent intent = new Intent(ACTION_AUTH_FAILED);
                                    intent.setPackage("com.kbs.kbsintranett");
                                    if (KbsApplication.getContext() != null) {
                                        KbsApplication.getContext().sendBroadcast(intent);
                                    }
                                }
                            }
                            return response;
                        }
                    })
                    .build();

            Gson gson = new GsonBuilder()
                    .registerTypeAdapter(new TypeToken<List<GravityField.Choice>>(){}.getType(), new ChoicesAdapter())
                    .setLenient()
                    .create();

            retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .client(client)
                    .addConverterFactory(GsonConverterFactory.create(gson))
                    .build();
        }
        return retrofit.create(WordPressApiService.class);
    }

    public static void clearClient() {
        retrofit = null;
    }
}