package br.com.codetec.saudesabor.service;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

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

import java.io.IOException;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.util.concurrent.TimeUnit;

import br.com.codetec.saudesabor.R;
import br.com.codetec.saudesabor.model.ResponseEnderecos;
import br.com.codetec.saudesabor.ui.login.LoginActivity;
import br.com.codetec.saudesabor.utils.components.alert.CustomAlert;
import br.com.codetec.saudesabor.utils.components.progressdialog.ProgresDialogUtil;
import okhttp3.Call;
import okhttp3.EventListener;
import okhttp3.JavaNetCookieJar;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;


public abstract class ServiceConector {

    public static final String BASE_URL = "http://saudeesabor.codecrm.com.br";

    public static final String TERMOS_DE_USO_URL = "http://codecrm.com.br/privacidade.php";

    private static SaudeSaborService service;

    private static Context context;
    private static String mensagemProgresso;

    private ResponseEnderecos responseEnderecos;


    public static SaudeSaborService getService(final Context _context) {
        return getService(_context, null);
    }

    public static SaudeSaborService getService(final Context _context, final String _mensagemProgresso) {
        context = _context;
        mensagemProgresso = _mensagemProgresso;
        if (service == null) {
            HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
            interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

            // init cookie manager
            CookieHandler cookieHandler = new CookieManager();

            OkHttpClient client = new OkHttpClient.Builder().addNetworkInterceptor(interceptor)
//                    .addInterceptor(interceptor1)
                    .cookieJar(new JavaNetCookieJar(cookieHandler))
                    .connectTimeout(10, TimeUnit.SECONDS)
                    .writeTimeout(10, TimeUnit.SECONDS)
                    .readTimeout(30, TimeUnit.SECONDS)
                    .eventListener(new EventListener() {
                        ProgresDialogUtil mProgresDialogUtil;

                        @Override
                        public void callStart(Call call) {
                            if (!isNetworkAvailable()) {
                                if(context!=null)
                                    CustomAlert.getInstance().show(context, context.getString(R.string.app_name), "Verifique sua conexão com a internet.");
                            }
                            if (mProgresDialogUtil == null || mProgresDialogUtil.getmContext() != context) {
                                mProgresDialogUtil = new ProgresDialogUtil(context);
                            }
                            if(context!=null && context.getString(R.string.app_name) !=null) {
                                mProgresDialogUtil.show(context.getString(R.string.app_name), mensagemProgresso == null ? "Processando" : mensagemProgresso);
                            }
                            super.callStart(call);
                        }

                        @Override
                        public void callEnd(Call call) {
                            fecharProgress();
                            super.callEnd(call);
                        }

                        @Override
                        public void callFailed(Call call, IOException ioe) {
//                            CustomAlert.getInstance().show(context, context.getString(R.string.app_name), ioe.getLocalizedMessage());
                            fecharProgress();
                        }

                        @Override
                        public void requestBodyEnd(Call call, long byteCount) {
                            fecharProgress();
                            super.requestBodyEnd(call, byteCount);
                        }

                        private void fecharProgress() {
                            if (mProgresDialogUtil != null) {
                                mProgresDialogUtil.dismiss();
                            }
                        }

                        @Override
                        public void requestHeadersEnd(Call call, Request request) {
                            fecharProgress();
                            super.requestHeadersEnd(call, request);
                        }
                    })
                    .build();

            Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss").create();

//            Gson gson = new GsonBuilder().setDateFormat(DateFormat.FULL).create();

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

            service = retrofit.create(SaudeSaborService.class);
        }
        return service;
    }

    private static boolean isNetworkAvailable() {
        if(LoginActivity.getInstance()!=null) {
            ConnectivityManager connectivityManager
                    = (ConnectivityManager) LoginActivity.getInstance().getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
            return activeNetworkInfo != null && activeNetworkInfo.isConnected();
        }else{
            return false;
        }
    }
}
