package cpm.com.gskmtorange.dailyentry;

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.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.CardView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.crashlytics.android.Crashlytics;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import org.xmlpull.v1.XmlPullParserException;

import java.io.IOException;
import java.io.InterruptedIOException;
import java.io.StringReader;
import java.net.MalformedURLException;
import java.net.SocketTimeoutException;
import java.util.ArrayList;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

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.StoreWisePerformanceActivity;
import cpm.com.gskmtorange.xmlHandlers.FailureXMLHandler;

public class ConversationActivity extends AppCompatActivity {

    String userId, culture_id, store_id, chat_id, message_main, visit_date;
    private SharedPreferences preferences = null;

    GSKOrangeDB db;

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

    MyRecyclerAdapter adapter;
    RecyclerView rec;

    EditText et_reply;
    private Dialog dialog;
    private ProgressBar pb;
    private TextView percentage, message;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_conversation);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

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

        rec = (RecyclerView) findViewById(R.id.rec_conversation);
        et_reply = (EditText) findViewById(R.id.et_reply);

        chat_id = getIntent().getStringExtra(CommonString.KEY_CHAT_ID);
        message_main = getIntent().getStringExtra(CommonString.KEY_MESSAGE);

        setTitle(message_main);

        preferences = PreferenceManager.getDefaultSharedPreferences(this);

        CommonFunctions.updateLangResources(getApplicationContext(), 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);
        visit_date = preferences.getString(CommonString.KEY_DATE, null);

        conversation_list = db.getChatMessageCommentsData(store_id, chat_id);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String reply = et_reply.getText().toString();
                if (reply.equals("")) {
                    Snackbar.make(et_reply, R.string.reply_alert, Snackbar.LENGTH_SHORT).show();
                } else {

                   /* ChatMessageGetterSetter msg = new ChatMessageGetterSetter();
                    msg.setCHAT_ID("0");
                    msg.setMESSAGE("");
                    msg.setMESSAGEDATE(visit_date);
                    msg.setSENDERID("0");
                    msg.setSENDER(userId);
                    msg.setRECEIVERID("0");
                    msg.setRECEIVER(userId);
                    msg.setSTOREID(store_id);
                    msg.setCOMMENTDATE(visit_date);
                    msg.setCOMMENT(reply);
                    msg.setSENDER_USERID(userId);

                    conversation_list.add(msg);

                    adapter.notifyDataSetChanged();

                    et_reply.setText("");*/

                    // Check if no view has focus:
                    View v = getCurrentFocus();
                    if (v != null) {
                        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                        imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                    }

                    new GeoTagUpload(ConversationActivity.this).execute(reply);
                }
            }
        });

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

    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
    }

    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 MyRecyclerAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = inflator.inflate(R.layout.conversation_item, parent, false);

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

            return holder;
        }

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

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

            final String msg_topic_str = data.get(position).getCOMMENT();
            final String latest_msg_str = data.get(position).getRECEIVER();
            final String date_time_str = data.get(position).getCOMMENTDATE();
            final String msg_from_str = data.get(position).getSENDER();
            final String sender_user_id = data.get(position).getSENDER_USERID();

            if (sender_user_id.equals(userId)) {
                LinearLayout.LayoutParams buttonLayoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                buttonLayoutParams.setMargins(100, 10, 5, 0);
                holder.parent_item.setLayoutParams(buttonLayoutParams);
                holder.card_view.setCardBackgroundColor(getResources().getColor(R.color.char_card_bg));
            } else {
                LinearLayout.LayoutParams buttonLayoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                buttonLayoutParams.setMargins(5, 10, 100, 0);
                holder.parent_item.setLayoutParams(buttonLayoutParams);
                holder.card_view.setCardBackgroundColor(getResources().getColor(R.color.white));
            }

            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) {

                }
            });
        }

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

        class MyViewHolder extends RecyclerView.ViewHolder {

            TextView msg_topic, latest_msg, date_time, msg_from;
            LinearLayout parent_layout, parent_item;
            CardView card_view;

            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);
                parent_item = (LinearLayout) itemView.findViewById(R.id.parent_item);
                card_view = (CardView) itemView.findViewById(R.id.card_view);

            }

        }
    }

    public class GeoTagUpload extends AsyncTask<String, Void, String> {

        private Context context;

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

        @Override
        protected void onPreExecute() {

            super.onPreExecute();

            dialog = new Dialog(context);
            dialog.setContentView(R.layout.custom);
            dialog.setTitle(getResources().getString(R.string.dialog_title));
            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(String... params) {

            boolean flag_success = false;
            String strflag = "";
            try {

                GSKOrangeDB db = new GSKOrangeDB(ConversationActivity.this);
                db.open();
                String reply = params[0];

                SAXParserFactory saxPF = SAXParserFactory.newInstance();
                SAXParser saxP = saxPF.newSAXParser();
                XMLReader xmlR = saxP.getXMLReader();


                String current_xml = "";

                String onXML = "[CHAT_REPLY][CHAT_ID]"
                        + chat_id
                        + "[/CHAT_ID]"
                        + "[SENDER_ID]"
                        + "0"
                        + "[/SENDER_ID]"
                        + "[RECIEVER_ID]"
                        + "0"
                        + "[/RECIEVER_ID]"
                        + "[STORE_ID]"
                        + store_id
                        + "[/STORE_ID]"
                        + "[MESSAGE]"
                        + reply
                        + "[/MESSAGE]"
                        + "[USER_ID]"
                        + userId
                        + "[/USER_ID]"
                        + "[/CHAT_REPLY]";

                current_xml = "[DATA]" + onXML
                        + "[/DATA]";

                SoapObject request = new SoapObject(CommonString.NAMESPACE,
                        CommonString.METHOD_UPLOAD_CHAT_DATA);
                //request.addProperty("MID", "0");
                // request.addProperty("KEYS", "CURRENT_DATA");
                // request.addProperty("USERNAME", username);

                request.addProperty("onXML", current_xml);

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

                HttpTransportSE androidHttpTransport = new HttpTransportSE(
                        CommonString.URL);
                androidHttpTransport.call(
                        CommonString.SOAP_ACTION_UPLOAD_CHAT_DATA, envelope);
                Object result = (Object) envelope.getResponse();

                if (result.toString().contains(
                        CommonString.KEY_SUCCESS)) {
                    flag_success = true;
                } else {
                    flag_success = false;
                }


            } catch (MalformedURLException e) {

                flag_success = false;
                strflag = CommonString.MESSAGE_EXCEPTION;

            } catch (SocketTimeoutException e) {
                flag_success = false;
                strflag = CommonString.MESSAGE_SOCKETEXCEPTION;

            } catch (InterruptedIOException e) {

                flag_success = false;
                strflag = CommonString.MESSAGE_EXCEPTION;

            } catch (IOException e) {
                flag_success = false;
                strflag = CommonString.MESSAGE_SOCKETEXCEPTION;
            } catch (XmlPullParserException e) {
                Crashlytics.log(7, CommonString.MESSAGE_EXCEPTION, e.toString());
                Crashlytics.logException(e.getCause());
                Crashlytics.logException(new Exception(e.getCause()));

                flag_success = false;
                strflag = CommonString.MESSAGE_XmlPull;
            } catch (Exception e) {
                Crashlytics.log(7, CommonString.MESSAGE_EXCEPTION, e.toString());
                Crashlytics.logException(e.getCause());
                Crashlytics.logException(new Exception(e.getCause()));

                flag_success = false;
                strflag = CommonString.MESSAGE_EXCEPTION;
            }

            if (flag_success) {
                return CommonString.KEY_SUCCESS;
            } else {
                return strflag;
            }
        }

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

            dialog.dismiss();

            if (result.equalsIgnoreCase(CommonString.KEY_SUCCESS)) {
                dialog.dismiss();

                String reply = et_reply.getText().toString();

                ChatMessageGetterSetter msg = new ChatMessageGetterSetter();
                msg.setCHAT_ID("0");
                msg.setMESSAGE("");
                msg.setMESSAGEDATE(visit_date);
                msg.setSENDERID("0");
                msg.setSENDER(userId);
                msg.setRECEIVERID("0");
                msg.setRECEIVER(userId);
                msg.setSTOREID(store_id);
                msg.setCOMMENTDATE(visit_date);
                msg.setCOMMENT(reply);
                msg.setSENDER_USERID(userId);

                conversation_list.add(msg);

                adapter.notifyDataSetChanged();

                et_reply.setText("");
                //showAlert(getString(R.string.data_downloaded_successfully));
            } else {

                showAlert(getString(R.string.DataNot) + " " + result);
            }
        }

    }

    public void showAlert(String str) {

        AlertDialog.Builder builder = new AlertDialog.Builder(ConversationActivity.this);
        builder.setTitle("Parinaam");
        builder.setMessage(str).setCancelable(false)
                .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {


                        finish();

                    }
                });
        AlertDialog alert = builder.create();
        alert.show();
    }

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