package cpm.com.gskmtorange.dailyentry;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.graphics.Typeface;
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.Toolbar;
import android.text.InputFilter;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseExpandableListAdapter;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.ToggleButton;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import cpm.com.gskmtorange.Database.GSKOrangeDB;
import cpm.com.gskmtorange.R;
import cpm.com.gskmtorange.constant.CommonFunctions;
import cpm.com.gskmtorange.constant.CommonString;
import cpm.com.gskmtorange.gsk_dailyentry.MSL_Availability_StockFacingActivity;
import cpm.com.gskmtorange.xmlGetterSetter.AuditDataGetterSetter;
import cpm.com.gskmtorange.xmlGetterSetter.MSL_AvailabilityStockFacingGetterSetter;
import cpm.com.gskmtorange.xmlGetterSetter.POGGetterSetter;

public class POGQuestionsActivity extends AppCompatActivity {

    ExpandableListView expandableListView;

    String categoryName, categoryId, Error_Message = "";
    String store_id, visit_date, username, intime, date, keyAccount_id, class_id, storeType_id, camera_allow, country_id, pog_type_id;
    boolean isDialogOpen = true;
    private SharedPreferences preferences;
    int scrollPosition = 0;

    GSKOrangeDB db;

    List<MSL_AvailabilityStockFacingGetterSetter> headerDataList;
    HashMap<MSL_AvailabilityStockFacingGetterSetter, List<POGGetterSetter>> hashMapListChildData = new HashMap<>();

    ExpandableListAdapter adapter;

    List<Integer> checkHeaderArray = new ArrayList<>();
    String error_msg="";
    boolean checkflag = true;

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

        expandableListView = (ExpandableListView) findViewById(R.id.expandableListView);

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

        //preference data
        preferences = PreferenceManager.getDefaultSharedPreferences(this);
        CommonFunctions.updateLangResources(getApplicationContext(), preferences.getString(CommonString.KEY_LANGUAGE, ""));
        store_id = preferences.getString(CommonString.KEY_STORE_ID, null);
        visit_date = preferences.getString(CommonString.KEY_DATE, null);
        date = preferences.getString(CommonString.KEY_DATE, null);
        username = preferences.getString(CommonString.KEY_USERNAME, null);
        intime = preferences.getString(CommonString.KEY_STORE_IN_TIME, "");
        keyAccount_id = preferences.getString(CommonString.KEY_KEYACCOUNT_ID, "");
        class_id = preferences.getString(CommonString.KEY_CLASS_ID, "");
        storeType_id = preferences.getString(CommonString.KEY_STORETYPE_ID, "");
        camera_allow = preferences.getString(CommonString.KEY_CAMERA_ALLOW, "");
        country_id = preferences.getString(CommonString.KEY_COUNTRY_ID, "");
        pog_type_id = preferences.getString(CommonString.KEY_POG_TYPE_ID, "");

        //Intent data
        categoryName = getIntent().getStringExtra("categoryName");
        categoryId = getIntent().getStringExtra("categoryId");

        //txt_mslAvailabilityName.setText(getResources().getString(R.string.title_activity_msl__availability));
        toolbar.setTitle(getResources().getString(R.string.pog));
        setSupportActionBar(toolbar);
        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (validateData()) {

                    AlertDialog.Builder builder = new AlertDialog.Builder(POGQuestionsActivity.this);
                    builder.setMessage(R.string.title_activity_Want_save)
                            .setCancelable(false)
                            .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int id) {

                                  db.savePOGQuestionAnswerData(hashMapListChildData, headerDataList,store_id, categoryId);
                                    finish();
                                    overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
                                }
                            })
                            .setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int id) {
                                    dialog.cancel();
                                }
                            });
                    AlertDialog alert = builder.create();
                    alert.show();
                } else {
                    adapter.notifyDataSetChanged();
                    expandableListView.invalidateViews();
                    Snackbar.make(expandableListView,error_msg , Snackbar.LENGTH_SHORT).show();
                }
            }
        });

        prepareListData();
    }


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

            android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(POGQuestionsActivity.this);
            builder.setTitle("Parinaam");
            builder.setMessage(getResources().getString(R.string.data_will_be_lost)).setCancelable(false)
                    .setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {

                            finish();
                            overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
                        }
                    })
                    .setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

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

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onBackPressed() {
        //super.onBackPressed();

        android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(POGQuestionsActivity.this);
        builder.setTitle("Parinaam");
        builder.setMessage(getResources().getString(R.string.data_will_be_lost)).setCancelable(false)
                .setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {

                        finish();
                        overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
                    }
                })
                .setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

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


    void prepareListData(){
        headerDataList = new ArrayList<>();

        headerDataList = db.getSubCategoryMasterForPOG(categoryId, storeType_id, pog_type_id);

        if (headerDataList.size() > 0) {
            for (int i = 0; i < headerDataList.size(); i++) {

                ArrayList<POGGetterSetter> quizDataList = db.getAfterSavePOGQuestionAnswerData(store_id, categoryId, headerDataList.get(i).getSub_category_id());

                if(quizDataList.size()==0){
                    quizDataList = db.getPOGSubCategoryWise(headerDataList.get(i).getSub_category_id(), pog_type_id, storeType_id);
                }

                 //hashMapListChildData = new HashMap<>();
                ArrayList<POGGetterSetter> childListData = new ArrayList<>();

                if (quizDataList.size() > 0) {
                    String select = getString(R.string.title_activity_select_dropdown);
                    // Adding child data
                    for (int j = 0; j < quizDataList.size();j++) {
                        childListData = db.getPOGAnswerData(quizDataList.get(j).getQUESTION_ID(), headerDataList.get(i).getSub_category_id(), select);
                        quizDataList.get(j).setAnswerList(childListData);
                    }
                }

                //childDataList = new ArrayList<>();
               /* childDataList = db.getMSL_Availability_StockFacingSKU_AfterSaveData(categoryId, headerDataList.get(i).getBrand_id(), store_id);
                if (!(childDataList.size() > 0)) {
                    childDataList = db.getPOGSubCategoryWise(categoryId, headerDataList.get(i).getBrand_id(), keyAccount_id, storeType_id, class_id);
                }*/

                hashMapListChildData.put(headerDataList.get(i), quizDataList);
            }
        }

        adapter = new ExpandableListAdapter(this, headerDataList, hashMapListChildData);
        expandableListView.setAdapter(adapter);

    }

    public class ExpandableListAdapter extends BaseExpandableListAdapter {
        private Context _context;
        private List<MSL_AvailabilityStockFacingGetterSetter> _listDataHeader;
        private HashMap<MSL_AvailabilityStockFacingGetterSetter, List<POGGetterSetter>> _listDataChild;

        public ExpandableListAdapter(Context context, List<MSL_AvailabilityStockFacingGetterSetter> listDataHeader,
                                     HashMap<MSL_AvailabilityStockFacingGetterSetter, List<POGGetterSetter>> listChildData) {
            this._context = context;
            this._listDataHeader = listDataHeader;
            this._listDataChild = listChildData;
        }

        @Override
        public Object getGroup(int groupPosition) {
            return this._listDataHeader.get(groupPosition);
        }

        @Override
        public int getGroupCount() {
            return this._listDataHeader.size();
        }

        @Override
        public long getGroupId(int groupPosition) {
            return groupPosition;
        }

        @Override
        public View getGroupView(final int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
            MSL_AvailabilityStockFacingGetterSetter headerTitle = (MSL_AvailabilityStockFacingGetterSetter) getGroup(groupPosition);

            if (convertView == null) {
                LayoutInflater infalInflater = (LayoutInflater) this._context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                convertView = infalInflater.inflate(R.layout.item_msl_availability_stock_facing_header, null, false);
            }

            TextView txt_categoryHeader = (TextView) convertView.findViewById(R.id.txt_categoryHeader);
            RelativeLayout rel_header = (RelativeLayout) convertView.findViewById(R.id.rel_categoryHeader);
            ImageView img_camera = (ImageView) convertView.findViewById(R.id.img_camera);
            CardView card_view = (CardView) convertView.findViewById(R.id.card_view);

            txt_categoryHeader.setTypeface(null, Typeface.BOLD);

            txt_categoryHeader.setText(headerTitle.getSub_category());


            if (!checkflag) {
                if (checkHeaderArray.contains(groupPosition)) {
                    card_view.setCardBackgroundColor(getResources().getColor(android.R.color.holo_red_dark));
                } else {
                    card_view.setCardBackgroundColor(getResources().getColor(R.color.grey_background));
                }
            }

            //empty check color change
            /*if (headerTitle.getCompany_id().equals("1")) {
                if (!checkflag) {
                    if (checkHeaderArray.contains(groupPosition)) {
                        //card_view.setCardBackgroundColor(getResources().getColor(android.R.color.holo_red_dark));
                        txt_categoryHeader.setTextColor(getResources().getColor(android.R.color.holo_red_dark));
                    } else {
                        txt_categoryHeader.setTextColor(getResources().getColor(R.color.colorPrimaryDark));
                    }
                }
            } else {
                if (!checkflag) {
                    if (checkHeaderArray.contains(groupPosition)) {
                        txt_categoryHeader.setTextColor(getResources().getColor(android.R.color.holo_red_dark));
                    } else {
                        txt_categoryHeader.setTextColor(getResources().getColor(R.color.black));
                    }
                }
            }*/

            return convertView;
        }

        @Override
        public Object getChild(int groupPosition, int childPosititon) {
            return this._listDataChild.get(this._listDataHeader.get(groupPosition)).get(childPosititon);
        }

        @Override
        public int getChildrenCount(int groupPosition) {
            return this._listDataChild.get(this._listDataHeader.get(groupPosition)).size();
        }

        @Override
        public long getChildId(int groupPosition, int childPosition) {
            return childPosition;
        }

        @Override
        public View getChildView(final int groupPosition, final int childPosition, boolean isLastChild,
                                 View convertView, ViewGroup parent) {

            final POGGetterSetter childData =
                    (POGGetterSetter) getChild(groupPosition, childPosition);
            ArrayList<POGGetterSetter> ans_list = childData.getAnswerList();
            ViewHolder holder = null;

            if (convertView == null) {
                LayoutInflater infalInflater = (LayoutInflater) this._context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                convertView = infalInflater.inflate(R.layout.pog_question, null, false);

                holder = new ViewHolder();
                holder.txt_question = (TextView) convertView.findViewById(R.id.txt_question);
                holder.sp_auditAnswer = (Spinner) convertView.findViewById(R.id.sp_auditAnswer);
                holder.cardView = (CardView) convertView.findViewById(R.id.card_view);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            holder.sp_auditAnswer.setAdapter(new AnswerSpinnerAdapter(POGQuestionsActivity.this, R.layout.custom_spinner_item, ans_list));

            final ArrayList<POGGetterSetter> finalAns_list = ans_list;
            holder.sp_auditAnswer.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                    POGGetterSetter ans = finalAns_list.get(position);
                    childData.setANSWER_ID(ans.getANSWER_ID());
                    childData.setANSWER(ans.getANSWER());

                }

                @Override
                public void onNothingSelected(AdapterView<?> parent) {

                }
            });

            holder.txt_question.setText(childData.getQUESTION() + " ("+childData.getQTYPE()+")");

            for (int i = 0; i < ans_list.size(); i++) {
                if ( ans_list.get(i).getANSWER_ID().equals(childData.getANSWER_ID())) {
                    holder.sp_auditAnswer.setSelection(i);
                    break;
                }
            }

            if(!checkflag){
                if(childData.getANSWER_ID().equals("0")){
                    holder.cardView.setCardBackgroundColor(getResources().getColor(android.R.color.holo_red_dark));

                }else {
                    holder.cardView.setCardBackgroundColor(getResources().getColor(R.color.white));
                }
            }

            return convertView;
        }

        @Override
        public boolean hasStableIds() {
            return false;
        }

        @Override
        public boolean isChildSelectable(int groupPosition, int childPosition) {
            return true;
        }
    }

    public class ViewHolder {
        CardView cardView;
        View mView;
        TextView txt_question;
        Spinner sp_auditAnswer;
    }

    public class AnswerSpinnerAdapter extends ArrayAdapter<POGGetterSetter> {
        List<POGGetterSetter> list;
        Context context;
        int resourceId;

        public AnswerSpinnerAdapter(Context context, int resourceId, ArrayList<POGGetterSetter> list) {
            super(context, resourceId, list);
            this.context = context;
            this.list = list;
            this.resourceId = resourceId;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            View view = convertView;
            LayoutInflater inflater = ((Activity) context).getLayoutInflater();
            view = inflater.inflate(resourceId, parent, false);
            POGGetterSetter cm = list.get(position);
            TextView txt_spinner = (TextView) view.findViewById(R.id.tv_text);
            txt_spinner.setText(list.get(position).getANSWER());

            return view;
        }

        @Override
        public View getDropDownView(int position, View convertView, ViewGroup parent) {
            View view = convertView;
            LayoutInflater inflater = ((Activity) context).getLayoutInflater();
            view = inflater.inflate(resourceId, parent, false);

            POGGetterSetter cm = list.get(position);

            TextView txt_spinner = (TextView) view.findViewById(R.id.tv_text);
            txt_spinner.setText(cm.getANSWER());

            return view;
        }
    }

    boolean validateData() {
        //boolean flag = true;
        checkHeaderArray.clear();

        checkflag = true;
        for(int l=0; l<headerDataList.size(); l++){

            List<POGGetterSetter> child_data = hashMapListChildData.get(headerDataList.get(l));
            for (int i = 0; i < child_data.size(); i++) {
                if (child_data.get(i).getANSWER_ID().equalsIgnoreCase("0")) {
                    error_msg = getString(R.string.pls_answer_all_qns);
                    checkflag = false;
                }

                if (checkflag == false) {
                    break;
                }
            }

            if (checkflag == false) {
                if (!checkHeaderArray.contains(l)) {
                    checkHeaderArray.add(l);
                }
                break;
            }
        }

        return checkflag;
    }
}
