package com.cygnusa.hyperm.service;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.cygnusa.hyperm.dbadapters.CommonDBHelper;
import com.cygnusa.hyperm.dbadapters.CustomerDetailsAdapter;
import com.cygnusa.hyperm.dbadapters.CustomerEnquiryDataAdapters;
import com.cygnusa.hyperm.dbadapters.TableConstants;
import com.cygnusa.hyperm.util.ApiService;
import com.cygnusa.hyperm.util.GlobalData;
import com.cygnusa.hyperm.util.MyCallback;
import com.cygnusa.hyperm.util.UtilService;
import com.cygnusa.hyperm.wrappers.AnswerResponse;
import com.cygnusa.hyperm.wrappers.CommonResponse;
import com.cygnusa.hyperm.wrappers.CustomerEnquiryModel;
import com.cygnusa.hyperm.wrappers.CustomerFeedbackModel;
import com.cygnusa.hyperm.wrappers.ErrorResponse;
import com.cygnusa.hyperm.wrappers.GetAllCustomerDetailsResponse;
import com.cygnusa.hyperm.wrappers.SendAllCustomerData;
import com.cygnusa.hyperm.wrappers.SendAllExploreDetailsModel;
import com.cygnusa.hyperm.wrappers.SendEnquiryDataModel;
import com.cygnusa.hyperm.wrappers.SingleTon;
import com.cygnusa.hyperm.wrappers.UserResponse;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class NetworkUpdateReceiver extends BroadcastReceiver {

    Context context;
    Retrofit restClient;
    String accessToken = "";

    @SuppressLint({"UnsafeProtectedBroadcastReceiver", "StaticFieldLeak"})
    public void onReceive(final Context context, Intent intent) {
        this.context = context;
        sendAssessmentService();
        sendCustDetailsService();
        sendEnquiryFormDetails();
        getAllOfflineAnswerSendToServer();
    }

    private void getAllOfflineAnswerSendToServer() {
        CustomerFeedbackModel customerFeedbackModel = new CustomerFeedbackModel();
        if (SingleTon.getInstance().feedbackModel.getCustomerData() != null && SingleTon.getInstance().feedbackModel.getCustomerData().size() > 0) {
            customerFeedbackModel = SingleTon.getInstance().feedbackModel;
        }

        restClient = new Retrofit.Builder()
                .baseUrl(GlobalData.SERVER_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .client(new OkHttpClient.Builder()
                        .readTimeout(60, TimeUnit.SECONDS)
                        .connectTimeout(60, TimeUnit.SECONDS)
                        .addInterceptor(new Interceptor() {
                            @Override
                            public Response intercept(Chain chain) throws IOException {
                                Request.Builder ongoing = chain.request().newBuilder();
                                ongoing.header("Authorization", accessToken);
                                ongoing.header("Accept", "application/json");
                                ongoing.method(chain.request().method(), chain.request().body());
                                return chain.proceed(ongoing.build());
                            }
                        })
                        .build())
                .build();
        ApiService apiService = restClient.create(ApiService.class);

        apiService.sendFeedBack(customerFeedbackModel).enqueue(new Callback<AnswerResponse>() {
            @Override
            public void onResponse(Call<AnswerResponse> call, retrofit2.Response<AnswerResponse> response) {
                if (response.body() != null && response.body().getStatus() == 200) {
                    SingleTon.getInstance().feedbackModel = new CustomerFeedbackModel();
                }
            }

            @Override
            public void onFailure(Call<AnswerResponse> call, Throwable t) {
            }
        });
    }

    private void sendEnquiryFormDetails() {

        CustomerEnquiryModel detailsModel = new CustomerEnquiryModel();
        CustomerEnquiryDataAdapters customerEnquiryDataAdapters = new CustomerEnquiryDataAdapters(context);
        List<SendEnquiryDataModel> getAllOfflineData = customerEnquiryDataAdapters.getAllEnquiryFromTable();
        List<SendEnquiryDataModel> allEnquiryData = new ArrayList<>();

        if (getAllOfflineData != null && getAllOfflineData.size() > 0) {
            detailsModel.setEmp_code(GlobalData.user.getData().getEmp_code());
            detailsModel.setSmpin(GlobalData.user.getData().getSmpin());
            for (int i = 0; i < getAllOfflineData.size(); i++) {
                Log.e("Name", getAllOfflineData.get(i).getVariantId());

                SendEnquiryDataModel customerData = new SendEnquiryDataModel();
                customerData.setModelId(getAllOfflineData.get(i).getModelId());
                customerData.setIsBrochure(getAllOfflineData.get(i).getIsBrochure());
                customerData.setEmail(getAllOfflineData.get(i).getEmail());
                customerData.setName(getAllOfflineData.get(i).getName());
                customerData.setVariantId(getAllOfflineData.get(i).getVariantId());
                customerData.setMobile(getAllOfflineData.get(i).getMobile());
                customerData.setUid(getAllOfflineData.get(i).getUid());
                allEnquiryData.add(customerData);

            }

            restClient = new Retrofit.Builder()
                    .baseUrl(GlobalData.SERVER_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .client(new OkHttpClient.Builder()
                            .readTimeout(60, TimeUnit.SECONDS)
                            .connectTimeout(60, TimeUnit.SECONDS)
                            .addInterceptor(new Interceptor() {
                                @Override
                                public Response intercept(Chain chain) throws IOException {
                                    Request.Builder ongoing = chain.request().newBuilder();
                                    ongoing.header("Authorization", accessToken);
                                    ongoing.header("Accept", "application/json");
                                    ongoing.method(chain.request().method(), chain.request().body());
                                    return chain.proceed(ongoing.build());
                                }
                            })
                            .build())
                    .build();
            ApiService apiService = restClient.create(ApiService.class);

            if (allEnquiryData.size() > 0) {
                detailsModel.setCust_enquiry(allEnquiryData);
                apiService.sendAllCustomerEnquiry(detailsModel).enqueue(new Callback<CommonResponse>() {
                    @Override
                    public void onResponse(Call<CommonResponse> call, retrofit2.Response<CommonResponse> response) {
                        if (response.body() != null) {
                            if (response.body().getStatus() == 200) {
                                Log.e("success", response.body().getMessage());
                            } else {
                                Log.e("fail", response.body().getMessage());
                            }
                        } else {
                            if (response.errorBody() != null) {
                                Log.e("error", response.errorBody().toString());
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<CommonResponse> call, Throwable t) {
                    }
                });
            }
        }
    }

    private void sendCustDetailsService() {
        SendAllExploreDetailsModel detailsModel = new SendAllExploreDetailsModel();
        CustomerDetailsAdapter customerDetailsAdapter = new CustomerDetailsAdapter(context);
        List<SendAllCustomerData> getAllOfflineData = customerDetailsAdapter.getAllDataFromDB();
        List<SendAllCustomerData> allCustomerData = new ArrayList<>();
        if (getAllOfflineData.size() > 0) {
            detailsModel.setEmp_code(GlobalData.user.getData().getEmp_code());
            detailsModel.setSmpin(GlobalData.user.getData().getSmpin());

            for (int i = 0; i < getAllOfflineData.size(); i++) {
                Log.e("Name", getAllOfflineData.get(i).getFirstname());

                SendAllCustomerData customerData = new SendAllCustomerData();
                customerData.setSalutation(getAllOfflineData.get(i).getSalutation());
                customerData.setAge(getAllOfflineData.get(i).getAge());
                customerData.setEmail(getAllOfflineData.get(i).getEmail());
                customerData.setFirstname(getAllOfflineData.get(i).getFirstname());
                customerData.setLastname(getAllOfflineData.get(i).getLastname());
                customerData.setMobile(getAllOfflineData.get(i).getMobile());
                customerData.setUid(getAllOfflineData.get(i).getUid());
                allCustomerData.add(customerData);

            }
            if (allCustomerData.size() > 0)
                detailsModel.setCustomerData(allCustomerData);

            restClient = new Retrofit.Builder()
                    .baseUrl(GlobalData.SERVER_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .client(new OkHttpClient.Builder()
                            .readTimeout(60, TimeUnit.SECONDS)
                            .connectTimeout(60, TimeUnit.SECONDS)
                            .addInterceptor(new Interceptor() {
                                @Override
                                public Response intercept(Chain chain) throws IOException {
                                    Request.Builder ongoing = chain.request().newBuilder();
                                    ongoing.header("Authorization", accessToken);
                                    ongoing.header("Accept", "application/json");
                                    ongoing.method(chain.request().method(), chain.request().body());
                                    return chain.proceed(ongoing.build());
                                }
                            })
                            .build())
                    .build();
            ApiService apiService = restClient.create(ApiService.class);

            apiService.sendAllExploreDetails(detailsModel).enqueue(new Callback<GetAllCustomerDetailsResponse>() {
                @Override
                public void onResponse(Call<GetAllCustomerDetailsResponse> call, retrofit2.Response<GetAllCustomerDetailsResponse> response) {
                    if (response.body() != null) {
                        if (response.body().getStatus() == 200) {
                            Log.e("Message", "Local Value Updated");
                            CommonDBHelper.getInstance(context).deleteTableValues(TableConstants.TABLE_CUSTOMER_DETAILS);
                        } else if (response.errorBody() != null) {
                            Gson gson = new Gson();
                            ErrorResponse message = gson.fromJson(response.errorBody().charStream(), ErrorResponse.class);
                            Log.e("Message", String.valueOf(message));
                        }
                    }
                }

                @Override
                public void onFailure(Call<GetAllCustomerDetailsResponse> call, Throwable t) {
                }
            });
        }
    }

    private void sendAssessmentService() {
        if (new UtilService().isNetworkAvailable(context)) {
            GlobalData.openDatabase(this.context);
            Cursor cursor = GlobalData.sdb.rawQuery("select * from session", null);

            if (cursor.getCount() != 0) {
                cursor.moveToFirst();
                Gson gson = new Gson();
                UserResponse user = gson.fromJson(
                        cursor.getString(cursor.getColumnIndex("user")),
                        new TypeToken<UserResponse>() {
                        }.getType());
                accessToken = String.format("Bearer %s", user.getAccess_token().trim());

                restClient = new Retrofit.Builder()
                        .baseUrl(GlobalData.SERVER_URL)
                        .addConverterFactory(GsonConverterFactory.create())
                        .client(new OkHttpClient.Builder()
                                .readTimeout(60, TimeUnit.SECONDS)
                                .connectTimeout(60, TimeUnit.SECONDS)
                                .addInterceptor(new Interceptor() {
                                    @Override
                                    public Response intercept(Chain chain) throws IOException {
                                        Request.Builder ongoing = chain.request().newBuilder();
                                        ongoing.header("Authorization", accessToken);
                                        ongoing.header("Accept", "application/json");
                                        ongoing.method(chain.request().method(), chain.request().body());
                                        return chain.proceed(ongoing.build());
                                    }
                                })
                                .build())
                        .build();
                ApiService apiService = restClient.create(ApiService.class);
                try {
                    Cursor cursor1 = GlobalData.sdb.rawQuery("select * from assessment_answer", null);
                    if (cursor1.getCount() != 0) {
                        cursor1.moveToFirst();
                        HashMap<String, String> map;
                        for (int i = 0; i < cursor1.getCount(); i++) {
                            map = gson.fromJson(
                                    cursor1.getString(cursor1.getColumnIndex("assessment_answer")),
                                    new TypeToken<HashMap<String, String>>() {
                                    }.getType());
                            apiService.postAssessment(cursor1.getString(cursor1.getColumnIndex("assessment_id")), map)
                                    .enqueue(new MyCallback<AnswerResponse>(cursor1.getInt(cursor1.getColumnIndex("id"))) {
                                        @Override
                                        public void onResponse(Call<AnswerResponse> call, retrofit2.Response<AnswerResponse> response) {

                                            if (response.body() != null && response.body().getStatus() == 200) {
                                                Cursor cursor = GlobalData.sdb.rawQuery("select * from assessment_answer where id=" + id, null);
                                                if (cursor.getCount() > 0) {
                                                    cursor.moveToFirst();
                                                    GlobalData.sdb.execSQL("delete from assessment_question where assessment_id='"
                                                            + cursor.getString(cursor.getColumnIndex("assessment_id"))
                                                            + "' and category_id='" + cursor.getString(cursor.getColumnIndex("category_id"))
                                                            + "' and training_id='" + cursor.getString(cursor.getColumnIndex("training_id")) + "'");

                                                    GlobalData.sdb.execSQL("delete from assessment where assessment_id='"
                                                            + cursor.getString(cursor.getColumnIndex("assessment_id"))
                                                            + "' and category_id='" + cursor.getString(cursor.getColumnIndex("category_id"))
                                                            + "' and training_id='" + cursor.getString(cursor.getColumnIndex("training_id")) + "'");

                                                    GlobalData.sdb.execSQL("delete from assessment_answer where id=" + id);
                                                }

                                            } else if (response.body() != null) {
                                                GlobalData.sdb.execSQL("update assessment_answer set error='"
                                                        + response.body().getMessage() + "' where id=" + id);
                                            } else if (response.errorBody() != null) {
                                                Gson gson = new Gson();
                                                ErrorResponse message = gson.fromJson(response.errorBody().charStream(), ErrorResponse.class);
                                                GlobalData.sdb.execSQL("update assessment_answer set error='"
                                                        + message.getMessage() + "' where id=" + id);
                                            }
                                        }

                                        @Override
                                        public void onFailure(Call<AnswerResponse> call, Throwable t) {

                                        }
                                    });
                            cursor1.moveToNext();
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}