package com.cpm.lorealbaMabeline.retrofit;

import android.content.Context;

import androidx.annotation.NonNull;

import com.cpm.lorealbaMabeline.constant.CommonString;
import com.cpm.lorealbaMabeline.gettersetter.ReferenceVariablesForDownloadActivity;

import java.io.IOException;
import java.net.SocketTimeoutException;
import java.util.concurrent.TimeUnit;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;


/**
 * Created by on 15/02/2019.
 */

public class UploadDataWithRetrofit extends ReferenceVariablesForDownloadActivity {

    boolean isvalid;
    Context context;
    int status = 0;

    public UploadDataWithRetrofit(Context context) {
        this.context = context;
    }


    public String uploadDeviceTokenDetails(String jsonString, int type) {
        try {
            status = 0;
            isvalid = false;
            final String[] data_global = {""};

            RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), jsonString);
            OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).writeTimeout(CommonString.TIMEOUT,
                    TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build();
            Retrofit adapter = new Retrofit.Builder().baseUrl(CommonString.URL).addConverterFactory(GsonConverterFactory.create()).client(okHttpClient).build();

            PostApi api = adapter.create(PostApi.class);
            Call<ResponseBody> call = null;

            if (type == CommonString.UPLOAD_DEVICE_TOKEN_DETAILS) {
                call = api.uploadTokenDetails(jsonData);
            } else {
                call = api.BACheckout(jsonData);
            }
            assert call != null;
            call.enqueue(new Callback<>() {
                @Override
                public void onResponse(@NonNull Call<ResponseBody> call, @NonNull Response<ResponseBody> response) {
                    ResponseBody responseBody = response.body();
                    String data = null;
                    if (responseBody != null && response.isSuccessful()) {
                        try {
                            data = response.body().string();
                            data = data.substring(1, data.length() - 1).replace("\\", "");
                            if (data.equalsIgnoreCase("")) {
                                data_global[0] = "";
                            } else {
                                data = data.substring(1, data.length() - 1).replace("\\", "");
                                data_global[0] = data;
                            }
                            isvalid = true;
                            status = 1;

                        } catch (Exception e) {
                            e.fillInStackTrace();
                            isvalid = true;
                            status = -2;
                        }
                    } else {
                        isvalid = true;
                        status = -1;
                    }
                }

                @Override
                public void onFailure(@NonNull Call<ResponseBody> call, @NonNull Throwable t) {
                    isvalid = true;
                    if (t instanceof SocketTimeoutException) {
                        status = 3;
                    } else if (t instanceof IOException) {
                        status = 3;
                    } else {
                        status = 3;
                    }
                }
            });

            if (type != CommonString.UPLOAD_DEVICE_TOKEN_DETAILS) {
                while (!isvalid) {
                    synchronized (this) {
                        this.wait(25);
                    }
                }
                if (isvalid) {
                    synchronized (this) {
                        this.notify();
                    }
                }
            }
            if (status == 1) {
                return data_global[0];
            } else if (status == 2) {
                return CommonString.MESSAGE_NO_RESPONSE_SERVER;
            } else if (status == 3) {
                return CommonString.MESSAGE_SOCKETEXCEPTION;
            } else if (status == -2) {
                return CommonString.MESSAGE_INVALID_JSON;
            } else {
                return CommonString.KEY_FAILURE;
            }
        } catch (Exception e) {
            e.fillInStackTrace();
            return CommonString.KEY_FAILURE;
        }
    }
}
