package com.younki.maidmatching.services;

import android.content.Context;

import com.younki.maidmatching.services.SharedPreference.Preferences;

import java.io.IOException;

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 ApiClient {
//    public static String getBaseUrl(){
//        return "http://192.168.1.7:8000";
//    }
    public static String getBaseUrl(){
        return "https://maidmatching.lol";
    }

    private static Retrofit getRetrofit(Context context){

        HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient okHttpClient;

        if (Preferences.getToken(context).isEmpty()) {
            okHttpClient = new OkHttpClient.Builder().addInterceptor(httpLoggingInterceptor).build();
        } else {
            okHttpClient = new OkHttpClient.Builder()
                    .addInterceptor(httpLoggingInterceptor)
                    .addInterceptor(new HeaderInterceptor(context))
                    .build();
        }

        Retrofit retrofit = new Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl(getBaseUrl()+"/api/")
                .client(okHttpClient)
                .build();

        return retrofit;

    }

    public static UserService getUserService(Context context){
        UserService userService = getRetrofit(context).create(UserService.class);

        return userService;
    }

    public static JobService getJobService(Context context){
        JobService jobService = getRetrofit(context).create(JobService.class);

        return jobService;
    }

    public static SkillService getSkillService(Context context){
        SkillService skillService = getRetrofit(context).create(SkillService.class);

        return skillService;
    }

    public static class HeaderInterceptor implements Interceptor {
        private Context mContext;

        public HeaderInterceptor(Context context) {
            mContext = context;
        }
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request originalRequest = chain.request();

            Request.Builder builder = originalRequest.newBuilder()
                    .header("Authorization", "Bearer "+Preferences.getToken(mContext));

            Request newRequest = builder.build();
            return chain.proceed(newRequest);
        }
    }

}
