package cpm.com.gskmtorange.pharma_stores;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.cardview.widget.CardView;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

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

import java.util.ArrayList;
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.xmlGetterSetter.MappingPharmaQuestionGetterSetter;
import cpm.com.gskmtorange.xmlGetterSetter.PharmaSOSGetterSetter;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link SOSFragment.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link SOSFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class SOSFragment extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;

    RecyclerView rec_sos;

    private SharedPreferences preferences;
    String store_id, visit_date, username, intime, keyAccount_id, class_id, storeType_id, country_id, store_flag_str;
    GSKOrangeDB db;

    FloatingActionButton fab;

    ArrayList<PharmaSOSGetterSetter> listBrandSubGroup;

    String Error_Message = "";
    int scrollPosition = 0;
    boolean checkflag = true;

    SOSAdapter adapter;

    public SOSFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment SOSFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static SOSFragment newInstance(String param1, String param2) {
        SOSFragment fragment = new SOSFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_so, container, false);

        preferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
        CommonFunctions.updateLangResources(getActivity(), preferences.getString(CommonString.KEY_LANGUAGE, ""));
        store_id = preferences.getString(CommonString.KEY_STORE_ID, null);
        visit_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, "");
        country_id = preferences.getString(CommonString.KEY_COUNTRY_ID, "");
        store_flag_str = preferences.getString(CommonString.KEY_STORE_FLAG, null);

        fab = (FloatingActionButton) getActivity().findViewById(R.id.fab);

        rec_sos = view.findViewById(R.id.rec_sos);

        getActivity().setTitle(R.string.sos_detail);

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

        prepareList();

        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                rec_sos.clearFocus();
                if(validateData(listBrandSubGroup)){
                    db.InsertSOSPharma(store_id, listBrandSubGroup);
                    onButtonPressed();
                }
                else {

                    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                    builder.setMessage(Error_Message)
                            .setCancelable(false)
                            .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int id) {
                                    adapter.notifyDataSetChanged();
                                    dialog.dismiss();
                                }
                            });
                    AlertDialog alert = builder.create();
                    alert.show();
                }

            }
        });

        return view;
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed() {
        if (mListener != null) {
            mListener.onFragmentInteraction(getActivity().getSupportFragmentManager().findFragmentById(R.id.fragment));
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            /*throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");*/
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Fragment uri);
    }

    void prepareList(){
        listBrandSubGroup = db.getStoreDetailPharmaForSOSData(store_id, "1");
        adapter = new SOSAdapter(getActivity());
        rec_sos.setAdapter(adapter);
        rec_sos.setLayoutManager(new LinearLayoutManager(getActivity()));
    }

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

        private LayoutInflater inflator;

        public SOSAdapter(Context context) {
            inflator = LayoutInflater.from(context);
            //this.data = data;
        }

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

            MyViewHolder holder = new MyViewHolder(view);



            return holder;
        }

        @Override
        public void onBindViewHolder(@NonNull MyViewHolder myViewHolder, int position) {
            final PharmaSOSGetterSetter current = listBrandSubGroup.get(position);

            /*holder.stock.setOnFocusChangeListener(new View.OnFocusChangeListener() {
                @Override
                public void onFocusChange(View v, boolean hasFocus) {
                    final EditText caption = (EditText) v;
                    String edStock = caption.getText().toString().replaceFirst("^0+(?!$)", "");*/
            myViewHolder.et_gsk_facing.setOnFocusChangeListener(new View.OnFocusChangeListener() {
                @Override
                public void onFocusChange(View v, boolean hasFocus) {
                    if(!hasFocus){
                        final EditText caption = (EditText) v;
                        String gskFacing = caption.getText().toString().replaceFirst("^0+(?!$)", "");

                        if(gskFacing.equals("")){
                            current.setGskFacing("");
                        }
                        else {
                            current.setGskFacing(gskFacing);
                        }
                    }
                }
            });

            myViewHolder.et_competitor_facing.setOnFocusChangeListener(new View.OnFocusChangeListener() {
                @Override
                public void onFocusChange(View v, boolean hasFocus) {
                    if(!hasFocus){
                        final EditText caption = (EditText) v;
                        String compFacing = caption.getText().toString().replaceFirst("^0+(?!$)", "");

                        if(compFacing.equals("")){
                            current.setCompetitorFacing("");
                        }
                        else {
                            current.setCompetitorFacing(compFacing);
                        }
                    }
                }
            });

            myViewHolder.tv_brand.setText(current.getSUB_CATEGORY() +" - "+ current.getBRAND());
            myViewHolder.et_gsk_facing.setText(current.getGskFacing());
            myViewHolder.et_competitor_facing.setText(current.getCompetitorFacing());

            if(!checkflag){
                if(current.getGskFacing()==null || current.getGskFacing().equals("") || current.getCompetitorFacing()==null || current.getCompetitorFacing().equals("")){
                    myViewHolder.card_view.setCardBackgroundColor(getResources().getColor(android.R.color.holo_red_dark));
                }
                else {
                    myViewHolder.card_view.setCardBackgroundColor(getResources().getColor(R.color.white));
                }
            }
        }

        @Override
        public int getItemCount() {

            return listBrandSubGroup.size();
        }

        class MyViewHolder extends RecyclerView.ViewHolder {

            TextView tv_brand;
            EditText et_gsk_facing, et_competitor_facing;
            CardView card_view;

            public MyViewHolder(@NonNull View itemView) {
                super(itemView);
                tv_brand = (TextView) itemView.findViewById(R.id.tv_brand);
                et_gsk_facing = (EditText) itemView.findViewById(R.id.et_gsk_facing);
                et_competitor_facing = (EditText) itemView.findViewById(R.id.et_competitor_facing);
                card_view = (CardView) itemView.findViewById(R.id.card_view);
            }
        }
    }

    boolean validateData(List<PharmaSOSGetterSetter> listData) {
        boolean flag = true, child_flag = true, all_flag = true;

        int childCount = 0;

        //temp list data for empty only
        List<MappingPharmaQuestionGetterSetter> listDataHeaderTemp = new ArrayList<>();

        flag = true;

            for (int j = 0; j < listData.size(); j++) {

                PharmaSOSGetterSetter data = listData.get(j);

                String gskFacing = data.getGskFacing();
                String competitionFacing = data.getCompetitorFacing();

                if(gskFacing==null || gskFacing.equals("")){

                    flag = false;
                    Error_Message = getResources().getString(R.string.enter_facing);
                    break;
                }
                else if (competitionFacing==null || competitionFacing.equals("")) {

                    flag = false;
                    Error_Message = getResources().getString(R.string.enter_facing);
                    break;
                }
                /*if (!child_flag)
                    listTemp.add(data);*/
            }

            if(flag){
                checkflag = true;
            }
            else {
                checkflag = false;
            }

       /* if (!all_flag) {
            adapter = new ExpandableListAdapter(this, listDataHeaderTemp, listDataChildTemp);
            expandableListView.setAdapter(adapter);
            checkflag = false;
        } else {
            checkflag = true;
        }*/

        return checkflag;
    }
}
