package com.ttiglobal.inttilectgpchat;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import androidx.core.content.ContextCompat;
import androidx.appcompat.app.AppCompatActivity;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.Patterns;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.MediaController;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.reflect.TypeToken;
import com.ttiglobal.inttilectgpchat.dbadapters.CommonDBHelper;
import com.ttiglobal.inttilectgpchat.dbadapters.CustomerDetailsAdapter;
import com.ttiglobal.inttilectgpchat.dbadapters.TableConstants;
import com.ttiglobal.inttilectgpchat.util.ApiService;
import com.ttiglobal.inttilectgpchat.util.CommonMethods;
import com.ttiglobal.inttilectgpchat.util.GlobalData;
import com.ttiglobal.inttilectgpchat.util.MainApplication;
import com.ttiglobal.inttilectgpchat.util.StorePreference;
import com.ttiglobal.inttilectgpchat.util.TransparentProgressDialog;
import com.ttiglobal.inttilectgpchat.wrappers.ErrorResponse;
import com.ttiglobal.inttilectgpchat.wrappers.GetAllCustomerDetailsResponse;
import com.ttiglobal.inttilectgpchat.wrappers.GetAllSalutationModel;
import com.ttiglobal.inttilectgpchat.wrappers.SendAllCustomerData;
import com.ttiglobal.inttilectgpchat.wrappers.SendAllExploreDetailsModel;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class ProductExploreDetailsActivity extends AppCompatActivity implements View.OnClickListener {
    Context context;
    private Button btn_get_started;
    private List<String> prefixDetailsSpinnerArray;
    Spinner spnPrefix;
    DisplayMetrics dm;
    MediaController media_Controller;
    private LinearLayout llout_get_started;
    private String ageRange = "";
    private EditText edtFirstName, edtLastName, edtMobileNumber, edtEmail;
    private TextView txtAgeFirst, txtAgeSecond, txtAgeThird, txtAgeFour, txtAgeFive;
    ApiService restService;
    ArrayAdapter<String> mGroupAdapter;
    List<SendAllExploreDetailsModel> detailsModelList;
    SendAllExploreDetailsModel detailsModel;
    StorePreference storePreference;
    boolean doubleBackToExitPressedOnce = false;
    private TransparentProgressDialog progressDialog;
    private LinearLayout whole_layout;
    private String currentTime = "";

    List<SendAllCustomerData> getAllOfflineData = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_product_explore_details);

        initViews();
        detailsModel = new SendAllExploreDetailsModel();

        if (CommonMethods.isNetworkAvailable(this)) {
            getAllSalutation();
            sendOfflineDataToServer();
        } else {
            getLocal();
        }
    }

    private void getLocal() {

        SharedPreferences pref = Objects.requireNonNull(ProductExploreDetailsActivity.this).getSharedPreferences("PRODUCT_MODULE", Context.MODE_PRIVATE);
        if (pref.getString("SALUTATION_" + storePreference.getStringValue(GlobalData.SALUTATION_MODEL), null) != null) {
            Gson gson = new Gson();
            prefixDetailsSpinnerArray = gson.fromJson(
                    pref.getString("SALUTATION_" + storePreference.getStringValue(GlobalData.SALUTATION_MODEL), null),
                    new TypeToken<List<String>>() {
                    }.getType());
            if (prefixDetailsSpinnerArray != null) {
                mGroupAdapter = new ArrayAdapter<>(context, R.layout.spinner_text_left, R.id.spinner_text, prefixDetailsSpinnerArray);
                spnPrefix.setAdapter(mGroupAdapter);
            }
        } else {
            Toast.makeText(ProductExploreDetailsActivity.this, "No data found", Toast.LENGTH_SHORT).show();
        }
    }

    private void getAllSalutation() {
        restService.getAllSaltuation().enqueue(new Callback<GetAllSalutationModel>() {
            @Override
            public void onResponse(Call<GetAllSalutationModel> call, Response<GetAllSalutationModel> response) {
                if (response.body() != null) {
                    if (response.body().getStatus() == 200) {
                        SharedPreferences pref = Objects.requireNonNull(ProductExploreDetailsActivity.this).getSharedPreferences("PRODUCT_MODULE", Context.MODE_PRIVATE);
                        SharedPreferences.Editor editor = pref.edit();
                        prefixDetailsSpinnerArray = response.body().getData();
                        if (prefixDetailsSpinnerArray.size() > 0) {
                            Gson gson = new Gson();
                            JsonElement jsonElement = gson.toJsonTree(
                                    prefixDetailsSpinnerArray, new TypeToken<List<String>>() {
                                    }.getType());
                            editor.putString("SALUTATION_" + storePreference.getStringValue(GlobalData.SALUTATION_MODEL),
                                    jsonElement.toString()).apply();

                            mGroupAdapter = new ArrayAdapter<>(context, R.layout.spinner_text_left, R.id.spinner_text, prefixDetailsSpinnerArray);
                            spnPrefix.setAdapter(mGroupAdapter);
                        } else {
                            getLocal();
                        }
                    } else if (response.body() != null && response.body().getStatus() == 401) {
                        GlobalData.canLogout = true;
                        finish();
                    } else if (response.errorBody() != null) {
                        Gson gson = new Gson();
                        ErrorResponse message = gson.fromJson(response.errorBody().charStream(), ErrorResponse.class);
                        GlobalData.showToast(getBaseContext(), message.getMessage(), Toast.LENGTH_SHORT).show();
                        if (message.getStatus() == 401) {
                            GlobalData.canLogout = true;
                            finish();
                        }
                    } else {
                        prefixDetailsSpinnerArray.add("-");
                        mGroupAdapter = new ArrayAdapter<>(context, R.layout.spinner_text_left, R.id.spinner_text, prefixDetailsSpinnerArray);
                        spnPrefix.setAdapter(mGroupAdapter);
                    }
                }
            }

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

    private void initViews() {
        context = this;
        spnPrefix = findViewById(R.id.spn_select_from);
        prefixDetailsSpinnerArray = new ArrayList<>();
        llout_get_started = findViewById(R.id.llout_get_started);
        btn_get_started = findViewById(R.id.btn_get_started);
        btn_get_started.setOnClickListener(this);
        llout_get_started.setOnClickListener(this);
        storePreference = new StorePreference(this);

        edtEmail = findViewById(R.id.edtEmail);
        edtFirstName = findViewById(R.id.edtFirstName);
        edtLastName = findViewById(R.id.edt_last_name);
        edtMobileNumber = findViewById(R.id.edtMobNumer);

        edtMobileNumber.setShowSoftInputOnFocus(false);
        edtEmail.setShowSoftInputOnFocus(false);
        edtFirstName.setShowSoftInputOnFocus(false);
        edtLastName.setShowSoftInputOnFocus(false);

        txtAgeFirst = findViewById(R.id.txtAgeFirst);
        txtAgeSecond = findViewById(R.id.txtAgeSecond);
        txtAgeThird = findViewById(R.id.txtAgeThird);
        txtAgeFour = findViewById(R.id.txtAgeFour);
        txtAgeFive = findViewById(R.id.txtAgeFive);

        txtAgeFive.setOnClickListener(this);
        txtAgeFour.setOnClickListener(this);
        txtAgeThird.setOnClickListener(this);
        txtAgeSecond.setOnClickListener(this);
        txtAgeFirst.setOnClickListener(this);
        progressDialog = new TransparentProgressDialog(ProductExploreDetailsActivity.this);
        whole_layout = findViewById(R.id.whole_lin_layout);
        whole_layout.setOnClickListener(this);

        restService = ((MainApplication) getApplication()).getClient();
    }

    @Override
    public void onBackPressed() {

        if (doubleBackToExitPressedOnce) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                finishAffinity();
            } else {
                System.exit(0);
                finish();
            }
            return;
        }

        this.doubleBackToExitPressedOnce = true;
        Toast.makeText(this, "Please click again to exit", Toast.LENGTH_SHORT).show();

        new Handler().postDelayed(new Runnable() {

            @Override
            public void run() {
                doubleBackToExitPressedOnce = false;
            }
        }, 2000);

    }

    private void loadVideo() {

        media_Controller = new MediaController(this);
        dm = new DisplayMetrics();
        this.getWindowManager().getDefaultDisplay().getMetrics(dm);
        int height = dm.heightPixels;
        int width = dm.widthPixels;
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.llout_get_started:
                currentTime = String.valueOf(System.currentTimeMillis());
                currentTime = GlobalData.user.getData().getEmp_code() + currentTime;
                storePreference.setString(GlobalData.CURRENTTIME, currentTime);
                sendOfflineDataToServer();
               // startActivity(new Intent(ProductExploreDetailsActivity.this, ProductHomeActivity.class));
                fieldValidation();
                break;
            case R.id.whole_lin_layout:
                hideKeyboard(ProductExploreDetailsActivity.this);
                break;
            case R.id.btn_get_started:
                currentTime = String.valueOf(System.currentTimeMillis());
                currentTime = GlobalData.user.getData().getEmp_code() + currentTime;
                storePreference.setString(GlobalData.CURRENTTIME, currentTime);
                sendOfflineDataToServer();
                fieldValidation();
                break;
            case R.id.txtAgeFirst:
                clickSelectedAgeRange(txtAgeFirst, txtAgeSecond, txtAgeThird, txtAgeFour, txtAgeFive);
                ageRange = txtAgeFirst.getText().toString();
                break;
            case R.id.txtAgeSecond:
                clickSelectedAgeRange(txtAgeSecond, txtAgeFirst, txtAgeThird, txtAgeFour, txtAgeFive);
                ageRange = txtAgeSecond.getText().toString();
                break;
            case R.id.txtAgeThird:
                clickSelectedAgeRange(txtAgeThird, txtAgeFirst, txtAgeSecond, txtAgeFour, txtAgeFive);
                ageRange = txtAgeThird.getText().toString();
                break;
            case R.id.txtAgeFour:
                clickSelectedAgeRange(txtAgeFour, txtAgeFirst, txtAgeSecond, txtAgeThird, txtAgeFive);
                ageRange = txtAgeFour.getText().toString();
                break;
            case R.id.txtAgeFive:
                clickSelectedAgeRange(txtAgeFive, txtAgeFirst, txtAgeSecond, txtAgeThird, txtAgeFour);
                ageRange = txtAgeFive.getText().toString();
                break;
            default:
        }
    }

    private void hideKeyboard(Activity activity) {
        InputMethodManager inputMethodManager =
                (InputMethodManager) activity.getSystemService(
                        Activity.INPUT_METHOD_SERVICE);
        inputMethodManager.hideSoftInputFromWindow(
                activity.getCurrentFocus().getWindowToken(), 0);
    }

    private void fieldValidation() {
        if (edtFirstName.getText().toString().equalsIgnoreCase("")) {
            CommonMethods.showToast(context, "Enter your name.").show();
        } else if (edtMobileNumber.getText().toString().equalsIgnoreCase("")) {
            CommonMethods.showToast(context, "Enter your mobile number.").show();
        } else if (!Patterns.PHONE.matcher(edtMobileNumber.getText().toString()).matches()) {
            CommonMethods.showToast(context, "Enter your valid mobile number.").show();
        } else if (edtMobileNumber.getText().length() < 10) {
            CommonMethods.showToast(context, "Enter your valid mobile number.").show();
        } else if (ageRange.equalsIgnoreCase("")) {
            CommonMethods.showToast(context, "Select age range.").show();
        } else {
            storePreference.setString(GlobalData.PRODUCT_NAME, edtFirstName.getText().toString().trim());
            if (CommonMethods.isNetworkAvailable(this)) {
                sendOfflineDataToServer();
                sendDetailsToServer();
            } else {
                insertDetailsToServer();
            }
        }
    }

    private void sendOfflineDataToServer() {
        SendAllExploreDetailsModel detailsModel = new SendAllExploreDetailsModel();
        CustomerDetailsAdapter customerDetailsAdapter = new CustomerDetailsAdapter(ProductExploreDetailsActivity.this);
        getAllOfflineData = customerDetailsAdapter.getAllDataFromDB();
        List<SendAllCustomerData> allCustomerData = 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).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);
            restService.sendAllExploreDetails(detailsModel).enqueue(new Callback<GetAllCustomerDetailsResponse>() {
                @Override
                public void onResponse(Call<GetAllCustomerDetailsResponse> call, Response<GetAllCustomerDetailsResponse> response) {
                    if (progressDialog != null && progressDialog.isShowing()) {
                        progressDialog.dismiss();
                    }
                    if (response.body() != null) {
                        if (response.body().getStatus() == 200) {
                            Log.e("Message", "Local Value Updated");
                            CommonDBHelper.getInstance(getApplicationContext()).deleteTableValues(TableConstants.TABLE_CUSTOMER_DETAILS);
                        } else if (response.errorBody() != null) {
                            Gson gson = new Gson();
                            ErrorResponse message = gson.fromJson(response.errorBody().charStream(), ErrorResponse.class);
                            GlobalData.showToast(getBaseContext(), message.getMessage(), Toast.LENGTH_SHORT).show();
                        } else {
                            CommonMethods.showToast(context, response.body().getMessage()).show();
                        }
                    }
                }

                @Override
                public void onFailure(Call<GetAllCustomerDetailsResponse> call, Throwable t) {
                    if (progressDialog != null && progressDialog.isShowing()) {
                        progressDialog.dismiss();
                    }
                }
            });
        }
    }

    private void insertDetailsToServer() {
        CustomerDetailsAdapter customerDetailsAdapter = new CustomerDetailsAdapter(ProductExploreDetailsActivity.this);
        if (!CustomerDetailsAdapter.checkRecordExists(edtMobileNumber.getText().toString())) {
            customerDetailsAdapter.insertLoginDetails(currentTime, spnPrefix.getSelectedItem().toString(), edtFirstName.getText().toString(), edtMobileNumber.getText().toString(), edtEmail.getText().toString(), ageRange);
            startActivity(new Intent(ProductExploreDetailsActivity.this, ProductHomeActivity.class));
        } else {
            startActivity(new Intent(ProductExploreDetailsActivity.this, ProductHomeActivity.class));
        }
    }


    private void sendDetailsToServer() {
        progressDialog.show();
        restService.sendAllExploreDetails(buildConfigData()).enqueue(new Callback<GetAllCustomerDetailsResponse>() {
            @Override
            public void onResponse(Call<GetAllCustomerDetailsResponse> call, Response<GetAllCustomerDetailsResponse> response) {
                if (progressDialog != null && progressDialog.isShowing()) {
                    progressDialog.dismiss();
                }
                if (response.body() != null) {
                    if (response.body().getStatus() == 200) {
                        Log.e("Message", response.body().getMessage());
                        storePreference.setString(GlobalData.DETAIL_NAME, edtFirstName.getText().toString());
                        storePreference.setString(GlobalData.DETAIL_EMAIL, edtEmail.getText().toString());
                        storePreference.setString(GlobalData.DETAIL_MOBILE, edtMobileNumber.getText().toString());
                        startActivity(new Intent(ProductExploreDetailsActivity.this, ProductHomeActivity.class));
                    } else if (response.errorBody() != null) {
                        Gson gson = new Gson();
                        ErrorResponse message = gson.fromJson(response.errorBody().charStream(), ErrorResponse.class);
                        GlobalData.showToast(getBaseContext(), message.getMessage(), Toast.LENGTH_SHORT).show();
                    } else {
                        CommonMethods.showToast(context, response.body().getMessage()).show();
                    }
                }
            }

            @Override
            public void onFailure(Call<GetAllCustomerDetailsResponse> call, Throwable t) {
                if (progressDialog != null && progressDialog.isShowing()) {
                    progressDialog.dismiss();
                }
            }
        });

    }

    private SendAllExploreDetailsModel buildConfigData() {
        SendAllExploreDetailsModel detailsModel = new SendAllExploreDetailsModel();
        detailsModel.setEmp_code(GlobalData.user.getData().getEmp_code());
        detailsModel.setSmpin(GlobalData.user.getData().getSmpin());
        List<SendAllCustomerData> allCustomerData = new ArrayList<>();
        SendAllCustomerData customerData = new SendAllCustomerData();
        customerData.setSalutation(spnPrefix.getSelectedItem().toString());
        customerData.setAge(ageRange);
        customerData.setEmail(edtEmail.getText().toString());
        customerData.setFirstname(edtFirstName.getText().toString());
        customerData.setLastname(edtLastName.getText().toString());
        customerData.setMobile(edtMobileNumber.getText().toString());
        customerData.setUid(currentTime);
        allCustomerData.add(customerData);
        detailsModel.setCustomerData(allCustomerData);
        return detailsModel;
    }

    private void clickSelectedAgeRange(TextView txtAgeFirst, TextView txtAgeSecond, TextView txtAgeThird, TextView txtAgeFour, TextView txtAgeFive) {
        txtAgeFirst.setBackground(ContextCompat.getDrawable(context, R.drawable.edt_border));
        txtAgeSecond.setBackground(ContextCompat.getDrawable(context, R.drawable.edt_unselected_border));
        txtAgeThird.setBackground(ContextCompat.getDrawable(context, R.drawable.edt_unselected_border));
        txtAgeFour.setBackground(ContextCompat.getDrawable(context, R.drawable.edt_unselected_border));
        txtAgeFive.setBackground(ContextCompat.getDrawable(context, R.drawable.edt_unselected_border));
    }
}
