package cpm.com.gskmtorange.dailyentry;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;

import cpm.com.gskmtorange.Database.GSKOrangeDB;
import cpm.com.gskmtorange.GetterSetter.CategoryPictureGetterSetter;
import cpm.com.gskmtorange.GetterSetter.CoverageBean;
import cpm.com.gskmtorange.R;
import cpm.com.gskmtorange.adapter.data.ImageUri;
import cpm.com.gskmtorange.constant.CommonFunctions;
import cpm.com.gskmtorange.constant.CommonString;
import cpm.com.gskmtorange.constant.CommonUtils;

public class CheckoutActivity extends AppCompatActivity {
    private Context context;
    private Dialog dialog;
    private ProgressBar pb;
    private TextView percentage, message;
    private String username, visit_date, store_id, store_flag_str;
    private Data data;
    private SharedPreferences preferences = null;
    GSKOrangeDB db;
    CoverageBean coverageBean;
    String lat, lon, checkOutImagePath = "";
    Toolbar toolbar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_checkout);
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        db = new GSKOrangeDB(this);
        db.open();
        context = this;
        preferences = PreferenceManager.getDefaultSharedPreferences(this);
        visit_date = preferences.getString(CommonString.KEY_DATE, null);
        username = preferences.getString(CommonString.KEY_USERNAME, null);
        CommonFunctions.updateLangResources(context, preferences.getString(CommonString.KEY_LANGUAGE, ""));
        store_id = getIntent().getStringExtra(CommonString.KEY_STORE_ID);
        store_flag_str = getIntent().getStringExtra(CommonString.KEY_STORE_FLAG);
        checkOutImagePath = getIntent().getStringExtra(CommonString.KEY_CHECKOUT_IMAGE);
        lat = getIntent().getStringExtra(CommonString.KEY_LATITUDE);
        lon = getIntent().getStringExtra(CommonString.KEY_LONGITUDE);
        coverageBean = db.getCoverageSpecificData(visit_date, store_id);
        new BackgroundTask(CheckoutActivity.this).execute();
    }

    private class BackgroundTask extends AsyncTask<Void, Data, String> {
        private Context context;

        BackgroundTask(Context context) {
            this.context = context;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            dialog = new Dialog(context);
            dialog.setContentView(R.layout.custom);
            dialog.setTitle(getString(R.string.title_activity_checkout));
            dialog.setCancelable(false);
            dialog.show();
            pb = (ProgressBar) dialog.findViewById(R.id.progressBar1);
            percentage = (TextView) dialog.findViewById(R.id.percentage);
            message = (TextView) dialog.findViewById(R.id.message);
        }

        @SuppressWarnings("deprecation")
        @Override
        protected String doInBackground(Void... params) {
            try {
                //String result = "";
                data = new Data();
                data.value = 20;
                data.name = "Checked out Data Uploading";
                publishProgress(data);
                String onXML = "[STORE_CHECK_OUT_STATUS]" + "[USER_ID]" + username + "[/USER_ID]" + "[STORE_ID]" + store_id + "[/STORE_ID]" + "[LATITUDE]" + lat + "[/LATITUDE]" + "[LOGITUDE]" + lon + "[/LOGITUDE]" + "[CHECKOUT_DATE]" + visit_date + "[/CHECKOUT_DATE]" + "[CHECK_OUTTIME]" + CommonFunctions.getCurrentTimeWithLanguage(context) + "[/CHECK_OUTTIME]" + "[CHECK_INTIME]" + coverageBean.getInTime() + "[/CHECK_INTIME]" + "[CREATED_BY]" + username + "[/CREATED_BY]" + "[/STORE_CHECK_OUT_STATUS]";
                final String sos_xml = "[DATA]" + onXML + "[/DATA]";
                String service;
                if (store_flag_str.equals(CommonString.FROM_ADDITIONAL) || store_flag_str.equals(CommonString.FROM_ADDITIONAL_ADHOC)) {
                    service = CommonString.METHOD_UPLOAD_CHECKOUT_STATUS_ADDITIONAL;
                } else if (store_flag_str.equals(CommonString.FROM_PHARMA)) {
                    service = CommonString.METHOD_UPLOAD_CHECKOUT_STATUS_PHARMA;
                } else {
                    service = CommonString.METHOD_UPLOAD_CHECKOUT_STATUS;
                }

                SoapObject request = new SoapObject(CommonString.NAMESPACE, service);
                request.addProperty("onXML", sos_xml);
                SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
                envelope.dotNet = true;
                envelope.setOutputSoapObject(request);

                HttpTransportSE androidHttpTransport = new HttpTransportSE(CommonString.URL);
                androidHttpTransport.call(CommonString.SOAP_ACTION + service, envelope);

                Object result = (Object) envelope.getResponse();

                if (!result.toString().equalsIgnoreCase(CommonString.KEY_SUCCESS)) {
                    return service;
                }
                if (result.toString().equalsIgnoreCase(CommonString.KEY_NO_DATA)) {
                    return service;
                }
                if (result.toString().equalsIgnoreCase(CommonString.KEY_FAILURE)) {
                    return service;
                }

                data.value = 100;
                data.name = "Checkout Done";
                publishProgress(data);

                if (result.toString().equalsIgnoreCase(CommonString.KEY_SUCCESS)) {
                    deleteIRURl();
                    db.open();
                    db.updateCheckoutOuttime(store_id, CommonFunctions.getCurrentTimeWithLanguage(context), CommonString.KEY_Y, checkOutImagePath);
                    SharedPreferences.Editor editor = preferences.edit();
                    editor.putString(CommonString.KEY_STORE_ID, "");
                    editor.putString(CommonString.KEY_STORE_NAME, "");
                    editor.putString(CommonString.KEY_VISIT_DATE, "");
                    editor.putString(CommonString.KEY_CAMERA_ALLOW, "");
                    editor.putString(CommonString.KEY_CHECKOUT_STATUS, "");
                    editor.putString(CommonString.KEY_CLASS_ID, "");
                    editor.putString(CommonString.KEY_EMP_ID, "");
                    editor.putString(CommonString.KEY_GEO_TAG, "");
                    editor.putString(CommonString.KEY_KEYACCOUNT_ID, "");
                    editor.putString(CommonString.KEY_STORETYPE_ID, "");
                    editor.putString(CommonString.KEY_UPLOAD_STATUS, "");
                    editor.commit();

                    String table;
                    switch (store_flag_str) {
                        case CommonString.FROM_JCP:
                            table = CommonString.KEY_JOURNEY_PLAN;
                            break;
                        case CommonString.FROM_ADDITIONAL:
                            table = CommonString.KEY_JOURNEY_PLAN_ADDITIONAL;
                            break;
                        case CommonString.FROM_PHARMA:
                            table = CommonString.KEY_JOURNEY_PLAN_PHARMA;
                            break;
                        case CommonString.FROM_ADDITIONAL_ADHOC:
                            table = CommonString.KEY_ADHOC_JOURNEYPLAN_ADDITIONAL;
                            break;
                        default:
                            table = CommonString.KEY_ADHOC_JOURNEY_PLAN;
                            break;
                    }

                    db.updateCheckoutStatus(store_id, CommonString.KEY_Y, table);
                } else {
                    if (result.toString().equalsIgnoreCase(CommonString.KEY_FALSE)) {
                        return service;
                    }
                }
                return CommonString.KEY_SUCCESS;

            } catch (MalformedURLException e) {
                runOnUiThread(() -> {
                    // TODO Auto-generated method stub
                    showAlert(CommonString.MESSAGE_EXCEPTION);
                });
            } catch (IOException e) {
                runOnUiThread(() -> showAlert(CommonString.MESSAGE_SOCKETEXCEPTION));
            } catch (Exception e) {
                runOnUiThread(() -> {
                    // TODO Auto-generated method stub
                    showAlert(CommonString.MESSAGE_EXCEPTION);
                });
            }

            return "";
        }

        @SuppressLint("SetTextI18n")
        @Override
        protected void onProgressUpdate(Data... values) {
            // TODO Auto-generated method stub
            pb.setProgress(values[0].value);
            percentage.setText(values[0].value + "%");
            message.setText(values[0].name);

        }

        @Override
        protected void onPostExecute(String result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
            dialog.dismiss();
            if (result.equalsIgnoreCase(CommonString.KEY_SUCCESS)) {
                showAlert(getString(R.string.checkout_successful));
            } else if (!result.equals("")) {
                Toast.makeText(context, "Network Error Try Again", Toast.LENGTH_SHORT).show();
                finish();
            }
        }
    }

    class Data {
        int value;
        String name;
    }

    @Override
    protected void onResume() {
        super.onResume();
        CommonFunctions.updateLangResources(context, preferences.getString(CommonString.KEY_LANGUAGE, ""));
        toolbar.setTitle(getResources().getString(R.string.title_activity_checkout));
    }

    private void deleteIRURl() {
        try {
            ArrayList<CategoryPictureGetterSetter> irList = db.getIrPDforUpload(store_id, visit_date);
            if (irList != null && !irList.isEmpty()) {
                for (int i = 0; i < irList.size(); i++) {
                    ArrayList<ImageUri> uris = irList.get(i).getImageUris();
                    if (uris != null && !uris.isEmpty()) {
                        for (int k = 0; k < uris.size(); k++) {
                            CommonUtils.INSTANCE.deleteSpecificImage(this,uris.get(k).getUri());
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.fillInStackTrace();
        }
    }

    public void showAlert(String str) {
        AlertDialog.Builder builder = new AlertDialog.Builder(CheckoutActivity.this);
        builder.setTitle("Parinaam");
        builder.setMessage(str).setCancelable(false).setPositiveButton("OK", (dialog, id) -> finish());
        AlertDialog alert = builder.create();
        alert.show();
    }
}
