package cpm.com.gskmtorange.dailyentry;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

//import com.crashlytics.android.Crashlytics;

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

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

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

import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;

import cpm.com.gskmtorange.Database.GSKOrangeDB;
import cpm.com.gskmtorange.GetterSetter.ChatMessageGetterSetter;
import cpm.com.gskmtorange.R;
import cpm.com.gskmtorange.constant.CommonFunctions;
import cpm.com.gskmtorange.constant.CommonString;
import cpm.com.gskmtorange.gsk_dailyentry.CategoryListActivity;
import cpm.com.gskmtorange.gsk_dailyentry.CategoryWisePerformanceActivity;
import cpm.com.gskmtorange.gsk_dailyentry.DailyDataMenuActivity;
import cpm.com.gskmtorange.xmlGetterSetter.ChatMessageDownloadGetterSetter;
import cpm.com.gskmtorange.xmlGetterSetter.TableBean;
import cpm.com.gskmtorange.xmlHandlers.XMLHandlers;

public class MessageActivity extends AppCompatActivity {
    //ArrayList<MessageGetterSetter> messages;
    private Context context;
    String categoryName = "", categoryId;

    MyRecyclerAdapter adapter;
    RecyclerView rec;

    private Dialog dialog;
    private ProgressBar pb;
    private TextView percentage, message;
    private Data data;
    int eventType;

    String userId, culture_id, store_id;
    private SharedPreferences preferences = null;

    GSKOrangeDB db;
    ArrayList<ChatMessageGetterSetter> chatmessagelist = new ArrayList<>();
    Toolbar toolbar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_message);
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        context = this;
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        rec = (RecyclerView)findViewById(R.id.rec);

        db = new GSKOrangeDB(MessageActivity.this);
        db.open();

        preferences = PreferenceManager.getDefaultSharedPreferences(this);

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

        userId = preferences.getString(CommonString.KEY_USERNAME, null);
        culture_id = preferences.getString(CommonString.KEY_CULTURE_ID, "");
        store_id = preferences.getString(CommonString.KEY_STORE_ID, null);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MessageActivity.this, CategoryListActivity.class);
                startActivity(intent);
                finish();
                overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
            }
        });

        //messages = getMessages();

       /* if(messages.size()>0){
            adapter = new MyRecyclerAdapter(getApplicationContext(), messages);
            rec.setAdapter(adapter);
            rec.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
        }*/

    }

    @Override
    protected void onResume() {
        super.onResume();
        CommonFunctions.updateLangResources(context, preferences.getString(CommonString.KEY_LANGUAGE, ""));
        toolbar.setTitle(getString(R.string.title_activity_message));
        new DowloadAsync(MessageActivity.this).execute();
    }

    /*ArrayList<MessageGetterSetter> getMessages(){
        ArrayList<MessageGetterSetter> messages = new ArrayList<>();

        for(int i=0; i<5;i++){
            MessageGetterSetter msg = new MessageGetterSetter();

            msg.setMessage("Store data need to be filled");
            msg.setFrom("Superviser"+(i+1));
            msg.setDate("11:20:32 11/06/2018");
            msg.setLatest_msg("Working on it");

            messages.add(msg);
        }
        return messages;
    }*/

    /*class MessageGetterSetter{

        String message="", from, date, latest_msg;

        public String getMessage() {
            return message;
        }

        public void setMessage(String message) {
            this.message = message;
        }

        public String getFrom() {
            return from;
        }

        public void setFrom(String from) {
            this.from = from;
        }

        public String getDate() {
            return date;
        }

        public void setDate(String date) {
            this.date = date;
        }

        public String getLatest_msg() {
            return latest_msg;
        }

        public void setLatest_msg(String latest_msg) {
            this.latest_msg = latest_msg;
        }
    }
*/
    class MyRecyclerAdapter extends RecyclerView.Adapter<MyRecyclerAdapter.MyViewHolder> {

        private LayoutInflater inflator;

        ArrayList<ChatMessageGetterSetter> data = new ArrayList<>();

        public MyRecyclerAdapter(Context context, ArrayList<ChatMessageGetterSetter> data) {

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

        }

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

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

            return holder;
        }

        @Override
        public void onBindViewHolder(MyViewHolder holder, final int position) {

            //final MappingPlanogramCountrywiseGetterSetter current = data.get(position);

            final String msg_topic_str = data.get(position).getMESSAGE();
            //final String latest_msg_str = data.get(position).getRECEIVER();
            final String date_time_str = data.get(position).getMESSAGEDATE();
            final String msg_from_str = data.get(position).getSENDER();

            holder.msg_topic.setText(msg_topic_str);
            //holder.latest_msg.setText(latest_msg_str);
            holder.date_time.setText(date_time_str);
            holder.msg_from.setText(msg_from_str);
            //holder.detail.setText(current.getDocument_descriiption().get(0));

            holder.parent_layout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent in = new Intent(MessageActivity.this, ConversationActivity.class);
                    in.putExtra(CommonString.KEY_CHAT_ID, data.get(position).getCHAT_ID());
                    in.putExtra(CommonString.KEY_MESSAGE, data.get(position).getMESSAGE());
                    startActivity(in);
                    overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
                }
            });
        }

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

        class MyViewHolder extends RecyclerView.ViewHolder {

            TextView msg_topic, latest_msg, date_time, msg_from;
            LinearLayout parent_layout;

            public MyViewHolder(View itemView) {
                super(itemView);
                msg_topic = (TextView) itemView.findViewById(R.id.tv_msg_topic);
                latest_msg = (TextView) itemView.findViewById(R.id.tv_latest_msg);
                date_time = (TextView) itemView.findViewById(R.id.tv_date_time);
                msg_from = (TextView) itemView.findViewById(R.id.tv_from);

                parent_layout = (LinearLayout) itemView.findViewById(R.id.layout_parent);

            }

        }
    }

    //region Download doc
    private class DowloadAsync extends AsyncTask<Void, Data, String> {

        private Context context;

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


        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            dialog = new Dialog(MessageActivity.this);
            dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            dialog.setContentView(R.layout.custom);
            //dialog.setTitle("Download Files");
            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);
        }

        @Override
        protected String doInBackground(Void... params) {

            data = new Data();
            String resultHttp = "";
            boolean flag = true;
            // JCP

            try {

                XmlPullParserFactory factory = null;
                factory = XmlPullParserFactory
                        .newInstance();

                factory.setNamespaceAware(true);
                XmlPullParser xpp = factory.newPullParser();

                SoapObject request = new SoapObject(CommonString.NAMESPACE,
                        CommonString.METHOD_NAME_UNIVERSAL_DOWNLOAD);
                request.addProperty("UserName", userId);
                request.addProperty("Type", "CHAT_MESSAGE");
                request.addProperty("cultureid", culture_id);


                SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
                        SoapEnvelope.VER11);
                envelope.dotNet = true;
                envelope.setOutputSoapObject(request);

                HttpTransportSE androidHttpTransport = new HttpTransportSE(
                        CommonString.URL);

                androidHttpTransport.call(CommonString.SOAP_ACTION_UNIVERSAL,
                        envelope);
                Object result = (Object) envelope.getResponse();

                if (result.toString() != null) {

                   xpp.setInput(new StringReader(result.toString()));
                    xpp.next();
                    eventType = xpp.getEventType();

                    ChatMessageDownloadGetterSetter chatmsg = XMLHandlers.CHAT_MESSAGE_XMLHandler(xpp, eventType);

                    if (chatmsg.getSENDERID().size() > 0) {
                        resultHttp = CommonString.KEY_SUCCESS;
                        String document_Table = chatmsg.getTable_CHAT_MESSAGE();

                        db.createTable(document_Table);
                        db.InserChatMessage(chatmsg);

                    } else {
                        return "CHAT_MESSAGE";
                    }

                    data.value = 10;
                    data.name = "Message Data Downloading";

                  /*  db.open();
                    db.InsertMappingCountrywisePlanogram(document);*/

                }

                publishProgress(data);

            } catch (XmlPullParserException e) {
                //Crashlytics.log(7, CommonString.MESSAGE_EXCEPTION, e.toString());
                //Crashlytics.logException(e.getCause());
               // Crashlytics.logException(new Exception(e.getCause()));
                e.printStackTrace();
                resultHttp = getString(R.string.nonetwork);
                flag = false;
            } catch (SoapFault soapFault) {
                soapFault.printStackTrace();
                resultHttp = getString(R.string.nonetwork);
                flag = false;
            } catch (IOException e) {
                e.printStackTrace();
                resultHttp = getString(R.string.nonetwork);
                flag = false;
            }
            catch ( Exception e){
                //Crashlytics.log(7, CommonString.MESSAGE_EXCEPTION, e.toString());
                //Crashlytics.logException(e.getCause());
                //Crashlytics.logException(new Exception(e.getCause()));
                resultHttp = getString(R.string.nonetwork);
                flag = false;
            }

            if(flag)
                return CommonString.KEY_SUCCESS;
            else
                return resultHttp;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);

            dialog.cancel();

            if (result.contains(CommonString.KEY_SUCCESS)) {

              /*  if(document.getPLANOGRAM_URL().size()>0){
                    adapter = new PlanogramPDFActivity.MyRecyclerAdapter(getApplicationContext(), document);
                    rec.setAdapter(adapter);
                    rec.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
                }
*/

            } else {
                //Snackbar.make(fab, result, Toast.LENGTH_SHORT).show();
            }

            db.open();
            chatmessagelist = db.getChatMessageData(store_id);

            if(chatmessagelist.size()>0){
                adapter = new MyRecyclerAdapter(context, chatmessagelist);
                rec.setAdapter(adapter);
                rec.setLayoutManager(new LinearLayoutManager(context));
            }

            //finish();
        }

        @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);

        }
    }
    //endregion

    class Data {
        int value;
        String name;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        if (id == android.R.id.home) {
            finish();
            overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
        }

        return super.onOptionsItemSelected(item);
    }
}
