package com.example.doctor_app_flutter.Service;

import android.app.Activity;
import android.app.Application;

import androidx.annotation.CallSuper;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.util.concurrent.TimeUnit;

import io.flutter.view.FlutterMain;
import okhttp3.ConnectionPool;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class AppRetrofit extends Application {
    private static final int MY_SOCKET_TIMEOUT_MS = 20000;

    @Override
    @CallSuper
    public void onCreate() {
        super.onCreate();
        FlutterMain.startInitialization(this);
    }

    private Activity mCurrentActivity = null;

    public Activity getCurrentActivity() {
        return mCurrentActivity;
    }

    public void setCurrentActivity(Activity mCurrentActivity) {
        this.mCurrentActivity = mCurrentActivity;
    }

    public static Retrofit getRetrofit( String baseUrl) {

        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        Gson gson = new GsonBuilder().serializeNulls().create();
        OkHttpClient okHttpClient = new OkHttpClient.Builder().addInterceptor(chain -> {
            okhttp3.Request originalRequest = chain.request();
            okhttp3.Request newRequest = originalRequest.newBuilder()
                    .addHeader("Content-Type","application/json")
                    .addHeader("Accept","application/json")
                    .build();

            return chain.proceed(newRequest);
        })
                .addInterceptor(interceptor)
                .callTimeout(MY_SOCKET_TIMEOUT_MS, TimeUnit.SECONDS)
                .connectTimeout(MY_SOCKET_TIMEOUT_MS, TimeUnit.SECONDS)
                .readTimeout(MY_SOCKET_TIMEOUT_MS, TimeUnit.SECONDS)
                .connectionPool(new ConnectionPool(0, 5 * 60 * 1000, TimeUnit.SECONDS))
                .retryOnConnectionFailure(false)
                .build();


        return new Retrofit.Builder()
                .baseUrl(baseUrl)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .client(okHttpClient)
                .build();
    }
}
