package cpm.com.gskmtorange.dailyentry;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

//import com.crashlytics.android.Crashlytics;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import cpm.com.gskmtorange.Database.GSKOrangeDB;
import cpm.com.gskmtorange.GetterSetter.StoreBean;
import cpm.com.gskmtorange.R;
import cpm.com.gskmtorange.constant.CommonFunctions;
import cpm.com.gskmtorange.constant.CommonString;
import cpm.com.gskmtorange.upload.UploadActivity;
import cpm.com.gskmtorange.upload.UploadImageWithRetrofit;
import cpm.com.gskmtorange.xmlGetterSetter.DeliveryCallsGetterSetter;

public class DeliveryCallActivity extends AppCompatActivity implements View.OnClickListener {
    private Context context;
    private SharedPreferences preferences;
    private GSKOrangeDB database;
    String visit_date, userId;
    ArrayList<DeliveryCallsGetterSetter> deliveryCallsList;
    RecyclerView recyclerView;
    DeliveryAdapter deliveryAdapter;
    FloatingActionButton fab_upload, fab;
    Toolbar toolbar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_delivery_call);
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        context = this;
        recyclerView = (RecyclerView) findViewById(R.id.rec_delivery_calls);
        fab = (FloatingActionButton) findViewById(R.id.fab);
        fab_upload = (FloatingActionButton) findViewById(R.id.fab_upload);

        preferences = PreferenceManager.getDefaultSharedPreferences(this);
        visit_date = preferences.getString(CommonString.KEY_DATE, null);
        userId = preferences.getString(CommonString.KEY_USERNAME, null);

        CommonFunctions.updateLangResources(context, preferences.getString(CommonString.KEY_LANGUAGE, ""));

        database = new GSKOrangeDB(this);
        database.open();

        fab.setOnClickListener(this);
        fab_upload.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {

        int id = v.getId();

        if (id == R.id.fab_upload) {
            new UploadTask().execute();
        } else if (id == R.id.fab) {
            if (isCheckedIn()) {
                Snackbar.make(recyclerView, getString(R.string.title_store_list_checkout_current), Snackbar.LENGTH_SHORT).show();
            } else {
                Intent in = new Intent(context, DeliveryCallAddStoreActivity.class);
                startActivity(in);
                overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
            }
        }

    }

    class DeliveryAdapter extends RecyclerView.Adapter<DeliveryAdapter.MyViewHolder> {

        private LayoutInflater inflator;

        List<DeliveryCallsGetterSetter> data = Collections.emptyList();

        public DeliveryAdapter(Context context, List<DeliveryCallsGetterSetter> data) {

            inflator = LayoutInflater.from(context);
            this.data = data;

        }

        @Override
        public DeliveryAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = inflator.inflate(R.layout.delivery_calls_item, parent, false);

            DeliveryAdapter.MyViewHolder holder = new DeliveryAdapter.MyViewHolder(view);

            return holder;
        }

        @Override
        public void onBindViewHolder(DeliveryAdapter.MyViewHolder holder, int position) {
            final DeliveryCallsGetterSetter current = data.get(position);
            holder.tv_store_name.setText(current.getSTORE_NAME());
            holder.tv_store_address.setText(current.getADDRESS());

            if (current.getUPLOAD_STATUS().equals(CommonString.KEY_CHECK_IN)) {
                holder.imageview.setVisibility(View.INVISIBLE);
                holder.cardView.setCardBackgroundColor(getResources().getColor(R.color.green));
            } else if (current.getUPLOAD_STATUS().equals(CommonString.KEY_U)) {
                holder.imageview.setVisibility(View.VISIBLE);
                holder.imageview.setBackgroundResource(R.mipmap.tick);
                holder.cardView.setCardBackgroundColor(getResources().getColor(R.color.colorOrange));
            } else if (current.getUPLOAD_STATUS().equals(CommonString.KEY_C)) {
                holder.imageview.setVisibility(View.VISIBLE);
                holder.imageview.setBackgroundResource(R.mipmap.exclamation);
                holder.cardView.setCardBackgroundColor(getResources().getColor(R.color.colorOrange));
            } else {
                holder.imageview.setVisibility(View.INVISIBLE);
                holder.cardView.setCardBackgroundColor(getResources().getColor(R.color.colorOrange));
            }

            holder.cardView.setOnClickListener(v -> {
                switch (current.getUPLOAD_STATUS()) {
                    case CommonString.KEY_CHECK_IN:
                        Intent in = new Intent(context, DeliveryCallAddStoreActivity.class);
                        in.putExtra(CommonString.KEY_STORE_ID, current);
                        in.putExtra(CommonString.KEY_STORE_FLAG, false);
                        startActivity(in);

                        overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
                        break;
                    case CommonString.KEY_U:
                        Snackbar.make(v, R.string.title_store_list_activity_store_already_done, Snackbar.LENGTH_LONG).setAction("Action", null).show();
                        break;
                    case CommonString.KEY_C:
                        Snackbar.make(v, R.string.title_store_list_activity_store_already_checkout, Snackbar.LENGTH_LONG).setAction("Action", null).show();
                        break;
                }
            });
        }

        @Override
        public int getItemCount() {
            return deliveryCallsList.size();
        }

        class MyViewHolder extends RecyclerView.ViewHolder {

            TextView tv_store_name, tv_store_address;
            CardView cardView;
            ImageView imageview;

            public MyViewHolder(View itemView) {
                super(itemView);

                tv_store_name = (TextView) itemView.findViewById(R.id.tv_store_name);
                tv_store_address = (TextView) itemView.findViewById(R.id.tv_store_address);
                cardView = (CardView) itemView.findViewById(R.id.card_view);
                imageview = (ImageView) itemView.findViewById(R.id.delivery_ico);
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        CommonFunctions.updateLangResources(context, preferences.getString(CommonString.KEY_LANGUAGE, ""));
        toolbar.setTitle(getString(R.string.delivery_call));
        deliveryCallsList = database.getDeliveryCallsData(visit_date);
        if (!deliveryCallsList.isEmpty()) {
            deliveryAdapter = new DeliveryAdapter(context, deliveryCallsList);
            recyclerView.setAdapter(deliveryAdapter);
            recyclerView.setLayoutManager(new LinearLayoutManager(this));
            if (isCheckedIn()) {
                fab_upload.hide();//setVisibility(View.GONE);
            } else if (isUploadAble()) {
                fab_upload.show();//setVisibility(View.VISIBLE);
            }
        }
    }

    private Dialog dialog;
    private ProgressBar pb;
    private TextView percentage, message;
    Object result = "";

    class Data {
        int value;
        String name;
    }

    class UploadTask extends AsyncTask<Void, Data, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            dialog = new Dialog(DeliveryCallActivity.this);
            dialog.setContentView(R.layout.custom);
            dialog.setTitle(getString(R.string.uploaddata));
            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);
            ((TextView) dialog.findViewById(R.id.tv_title)).setText(getString(R.string.uploaddata));
        }

        @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 String doInBackground(Void... voids) {
            try {
                Data data = new Data();
                ArrayList<DeliveryCallsGetterSetter> _deliveryCallsList = database.getDeliveryCallsData(null);
                for (int i = 0; i < _deliveryCallsList.size(); i++) {
                    if (_deliveryCallsList.get(i).getUPLOAD_STATUS().equals(CommonString.KEY_C)) {
                        data.value = 50;
                        data.name = getString(R.string.delivery_call);
                        publishProgress(data);
                        String store_name = URLEncoder.encode(_deliveryCallsList.get(i).getSTORE_NAME(), "utf-8");
                        String store_address = URLEncoder.encode(_deliveryCallsList.get(i).getADDRESS(), "utf-8");
                        String onXML = "[DELIVERY_CALLS_DATA]"
                                + "[USER_ID]" + userId + "[/USER_ID]"
                                + "[VISIT_DATE]" + _deliveryCallsList.get(i).getVISIT_DATE() + "[/VISIT_DATE]"
                                + "[STORE_NAME]" + store_name + "[/STORE_NAME]"
                                + "[STORE_ADDRESS]" + store_address + "[/STORE_ADDRESS]"
                                + "[IN_TIME]" + _deliveryCallsList.get(i).getIn_time() + "[/IN_TIME]"
                                + "[OUT_TIME]" + _deliveryCallsList.get(i).getOut_time() + "[/OUT_TIME]"
                                + "[IN_TIME_IMAGE]" + _deliveryCallsList.get(i).getIN_TIME_IMAGE() + "[/IN_TIME_IMAGE]"
                                + "[OUT_TIME_IMAGE]" + _deliveryCallsList.get(i).getOUT_TIME_IMAGE() + "[/OUT_TIME_IMAGE]"
                                + "[LATITUDE]" + _deliveryCallsList.get(i).getLATITUDE() + "[/LATITUDE]"
                                + "[LONGITUDE]" + _deliveryCallsList.get(i).getLONGITUDE() + "[/LONGITUDE]"
                                + "[/DELIVERY_CALLS_DATA]";

                        final String delivery_xml = "[DATA]" + onXML + "[/DATA]";

                        SoapObject request = new SoapObject(CommonString.NAMESPACE, CommonString.METHOD_UPLOAD_STOCK_XML_DATA);
                        request.addProperty("XMLDATA", delivery_xml);
                        request.addProperty("KEYS", "DELIVERY_CALLS");
                        request.addProperty("USERNAME", userId);
                        request.addProperty("MID", 0);
                        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
                        envelope.dotNet = true;
                        envelope.setOutputSoapObject(request);
                        HttpTransportSE androidHttpTransport = new HttpTransportSE(CommonString.URL);
                        androidHttpTransport.call(CommonString.SOAP_ACTION + CommonString.METHOD_UPLOAD_STOCK_XML_DATA, envelope);
                        result = envelope.getResponse();
                        if (!result.toString().equalsIgnoreCase(CommonString.KEY_SUCCESS)) {
                            return CommonString.METHOD_UPLOAD_STOCK_XML_DATA;
                        } else {
                            database.open();
                            database.updateDeliveryCallsUploadStatus(_deliveryCallsList.get(i).getId());
                        }
                    }
                }

                return result.toString();

            } catch (IOException e) {
                e.fillInStackTrace();
            } catch (XmlPullParserException e) {
                e.fillInStackTrace();
            } catch (Exception e) {
                e.fillInStackTrace();
            }

            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            dialog.dismiss();
            if (result.contains(CommonString.KEY_SUCCESS)) {
                //db.deleteAllTables();
                File f = new File(CommonString.getImagesFolder(context));
                File fileAll[] = f.listFiles();
                ArrayList<String> file_list = new ArrayList<>();
                for (int i = 0; i < fileAll.length; i++) {
                    String name = fileAll[i].getName();
                    if (name.contains("DeliveryCalls")) {
                        file_list.add(name);
                    }
                }

                UploadImageWithRetrofit.uploadedFiles = 0;
                UploadImageWithRetrofit.totalFiles = file_list.size();
                UploadImageWithRetrofit uploadImg = new UploadImageWithRetrofit(visit_date, userId, DeliveryCallActivity.this);
                uploadImg.UploadDeliveryImageRecursive(DeliveryCallActivity.this, file_list, 0);
            } else {
                showAlert(getString(R.string.error) + result.toString());
            }
        }
    }

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


    boolean isCheckedIn() {
        boolean flag = false;
        for (int i = 0; i < deliveryCallsList.size(); i++) {
            if (deliveryCallsList.get(i).getUPLOAD_STATUS().equals(CommonString.KEY_CHECK_IN)) {
                flag = true;
                break;
            }
        }
        return flag;
    }

    boolean isUploadAble() {
        boolean flag = false;
        for (int i = 0; i < deliveryCallsList.size(); i++) {
            if (deliveryCallsList.get(i).getUPLOAD_STATUS().equals(CommonString.KEY_C)) {
                flag = true;
                break;
            }
        }
        return flag;
    }
}
