package com.cygnusa.hyperm.fragments;


import android.annotation.SuppressLint;
import android.content.ClipData;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.DragEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ExpandableListView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.reflect.TypeToken;
import com.cygnusa.hyperm.LoginActivity;
import com.cygnusa.hyperm.ProductFeedbackFormActivity;
import com.cygnusa.hyperm.R;
import com.cygnusa.hyperm.HyperMEnquiryForm;
import com.cygnusa.hyperm.adapter.ComparisionChildAdapter;
import com.cygnusa.hyperm.adapter.ComparisionExpandableListAdapter;
import com.cygnusa.hyperm.util.ApiService;
import com.cygnusa.hyperm.util.CommonMethods;
import com.cygnusa.hyperm.util.GlobalData;
import com.cygnusa.hyperm.util.MainApplication;
import com.cygnusa.hyperm.util.StorePreference;
import com.cygnusa.hyperm.wrappers.ComparisonDataModel;
import com.cygnusa.hyperm.wrappers.ErrorResponse;
import com.cygnusa.hyperm.wrappers.RootGetAllComparisonModel;

import net.cachapa.expandablelayout.ExpandableLayout;

import java.util.Objects;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static com.cygnusa.hyperm.MainActivity.img_broucher;
import static com.cygnusa.hyperm.MainActivity.img_rating;
import static com.cygnusa.hyperm.MainActivity.layout1;

/**
 * Created by pavitha on 1/8/2018.
 */

public class HypermComparisonFragment extends Fragment implements AbsListView.OnScrollListener, ExpandableLayout.OnExpansionUpdateListener, View.OnClickListener {

    TextView productName;
    ImageView productImage;
    ExpandableListView cpMainList;
    LinearLayout childLayout, itemLayout, linearplacedrop;
    ComparisonDataModel MODELS;
    ComparisionExpandableListAdapter ADAPTER;
    private int clickId, closeClickId;
    LinearLayout layout;
    ProgressBar progressBar;
    StorePreference storePreference;
    ApiService restService;
    private ExpandableLayout expandableLayout;
    private ImageView expandButton;
    boolean isOpened = false;
    private ImageView imgNoData;
    private ScrollView lloutWhole;

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.activity_comparision_new, null);
    }


    @SuppressLint("ClickableViewAccessibility")
    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        view.findViewById(R.id.backButton).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Objects.requireNonNull(getActivity()).onBackPressed();

            }
        });
        expandableLayout = view.findViewById(R.id.expandable_layout);
        expandButton = view.findViewById(R.id.expand_button);

        expandableLayout.setOnExpansionUpdateListener(this);
        expandButton.setOnClickListener(this);

        storePreference = new StorePreference(getActivity());
        productName = view.findViewById(R.id.productName);
        productImage = view.findViewById(R.id.productImage);
        cpMainList = view.findViewById(R.id.cpMainList);
        childLayout = view.findViewById(R.id.childLayout);
        itemLayout = view.findViewById(R.id.itemLayout);
        linearplacedrop = view.findViewById(R.id.linearplacedrop);
        progressBar = view.findViewById(R.id.progress);
        progressBar.setVisibility(View.GONE);
        imgNoData = view.findViewById(R.id.noDataFound);
        imgNoData.setVisibility(View.GONE);
        lloutWhole = view.findViewById(R.id.whole_layout);
        restService = ((MainApplication) getActivity().getApplication()).getClient();
        cpMainList.setOnScrollListener(this);
        productName.setText(storePreference.getStringValue(GlobalData.SELECTED_MODEL_NAME));
        img_broucher.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getActivity(), HyperMEnquiryForm.class));
            }
        });
        img_rating.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getActivity(), ProductFeedbackFormActivity.class));
            }
        });
        layout1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getActivity(), HyperMEnquiryForm.class));
            }
        });
        cpMainList.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
            @Override
            public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
                for (int i = 0; i < childLayout.getChildCount(); i++) {
                    LinearLayout layout = (LinearLayout) childLayout.getChildAt(i);
                    ExpandableListView listView = (ExpandableListView) layout.getChildAt(1);
                    if (listView.isGroupExpanded(groupPosition)) {
                        listView.collapseGroup(groupPosition);
                    } else {
                        listView.expandGroup(groupPosition);
                    }
                }
                return false;
            }
        });

        if (CommonMethods.isNetworkAvailable(getActivity())) {
            getAllComparisonDetailsFromServer();
        } else {
            checkLocalComparition();
        }
        linearplacedrop.setOnDragListener(new View.OnDragListener() {
            @Override
            public boolean onDrag(View v, DragEvent event) {
                final int action = event.getAction();

                switch (action) {
                    case DragEvent.ACTION_DRAG_STARTED:
                        linearplacedrop.setVisibility(View.VISIBLE);
                        break;
                    case DragEvent.ACTION_DRAG_EXITED:
                        for (int j = 0; j < itemLayout.getChildCount(); j++) {
                            if (clickId == j) {
                                LinearLayout v1 = (LinearLayout) itemLayout.getChildAt(j);
                                LinearLayout Linear1 = (LinearLayout) v1.getChildAt(0);
                                ImageView text = (ImageView) Linear1.getChildAt(0);
                                TextView textView = (TextView) Linear1.getChildAt(1);
                                Linear1.setBackgroundColor(Color.parseColor("#000000"));
                                text.setAlpha(0.3f);
                                textView.setAlpha(0.3f);
                            }
                        }
                        break;
                    case DragEvent.ACTION_DRAG_ENTERED:
                        break;
                    case DragEvent.ACTION_DROP: {
                        LinearLayout v1;
                        for (int j = 0; j < itemLayout.getChildCount(); j++) {
                            if (clickId == j) {
                                v1 = (LinearLayout) itemLayout.getChildAt(j);
                                LinearLayout Linear1 = (LinearLayout) v1.getChildAt(0);
                                ImageView imageView = (ImageView) Linear1.getChildAt(0);
                                TextView textView = (TextView) Linear1.getChildAt(1);
                                Linear1.setBackgroundColor(Color.parseColor("#10000000"));
                                imageView.setAlpha(0.3f);
                                textView.setAlpha(0.3f);
                                Linear1.setEnabled(false);
                            }
                        }
                        if (MODELS.getComparisonCategoryList().size() > 0) {
                            ADAPTER = new ComparisionExpandableListAdapter(getActivity(), MODELS.getComparisonCategoryList());
                            cpMainList.setAdapter(ADAPTER);
                        }
                        addChildList(clickId);
                    }
                    break;
                    case DragEvent.ACTION_DRAG_ENDED: {
                        if (childLayout.getChildCount() > 0) {
                            linearplacedrop.setVisibility(View.GONE);
                        }
                        for (int j = 0; j < itemLayout.getChildCount(); j++) {
                            if (clickId == j) {
                                LinearLayout v1 = (LinearLayout) itemLayout.getChildAt(j);
                                LinearLayout Linear1 = (LinearLayout) v1.getChildAt(0);
                                ImageView text = (ImageView) Linear1.getChildAt(0);
                                TextView textView = (TextView) Linear1.getChildAt(1);
                                Linear1.setBackgroundColor(Color.parseColor("#40000000"));
                                text.setAlpha(1f);
                                textView.setAlpha(1f);
                                linearplacedrop.setBackgroundColor(Color.parseColor("#10000000"));
                            }
                        }
                    }
                    break;
                    default:
                }

                return true;
            }
        });
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
    }

    @Override
    public void onDetach() {
        super.onDetach();
    }
    private void getAllComparisonDetailsFromServer() {
        progressBar.setVisibility(View.VISIBLE);
        restService.getAllComparisonDetails(storePreference.getStringValue(GlobalData.SELECTED_MODEL)).enqueue(new Callback<RootGetAllComparisonModel>() {
            @Override
            public void onResponse(Call<RootGetAllComparisonModel> call, Response<RootGetAllComparisonModel> response) {
                progressBar.setVisibility(View.GONE);

                SharedPreferences pref = Objects.requireNonNull(getActivity()).getSharedPreferences("PRODUCT_MODULE", Context.MODE_PRIVATE);
                SharedPreferences.Editor editor = pref.edit();

                if (response.body() != null && response.body().getStatus() == 200) {
                    if (response.body().getDataModel() != null &&
                            response.body().getDataModel().getComparisonCategoryList().size() > 0) {

                        MODELS = response.body().getDataModel();
                        Gson gson = new Gson();
                        JsonElement jsonElement = gson.toJsonTree(
                                MODELS, new TypeToken<ComparisonDataModel>() {
                                }.getType());
                        editor.putString("COMPARITION_" + storePreference.getStringValue(GlobalData.SELECTED_MODEL),
                                jsonElement.toString()).apply();

                        Glide.with(getActivity()).load(MODELS
                                .getComparisonModelList().getModelImageUrl().trim()).into(productImage);
                        ADAPTER = new ComparisionExpandableListAdapter(getActivity(), MODELS.getComparisonCategoryList());
                        cpMainList.setAdapter(ADAPTER);
                        setItemLayout();
                    } else {
                        checkLocalComparition();
                    }
                } else if (response.body() != null && response.body().getStatus() == 401) {
                        GlobalData.canLogout = true;
                        startActivity(new Intent(getActivity(), LoginActivity.class));
                        Objects.requireNonNull(getActivity()).finish();

                } else if (response.body() != null && response.body().getStatus() == 406) {
                    checkLocalComparition();
                } else if (response.errorBody() != null) {
                    Gson gson = new Gson();
                    ErrorResponse message = gson.fromJson(response.errorBody().charStream(), ErrorResponse.class);
                    GlobalData.showToast(Objects.requireNonNull(getActivity()), message.getMessage(), Toast.LENGTH_SHORT).show();
                    if (message.getStatus() == 401) {
                        GlobalData.canLogout = true;
                        startActivity(new Intent(getActivity(), LoginActivity.class));
                        Objects.requireNonNull(getActivity()).finish();
                    }
                    checkLocalComparition();
                } else {
                    checkLocalComparition();
                }
            }

            @Override
            public void onFailure(Call<RootGetAllComparisonModel> call, Throwable t) {
                progressBar.setVisibility(View.GONE);
                if (t.getMessage() != null) {
                    CommonMethods.showToast(getActivity(), t.getMessage()).show();
                    checkLocalComparition();
                }
            }
        });
    }
    private void checkLocalComparition() {
        SharedPreferences pref = Objects.requireNonNull(getActivity()).getSharedPreferences("PRODUCT_MODULE", Context.MODE_PRIVATE);
        if (pref.getString("COMPARITION_" + storePreference.getStringValue(GlobalData.SELECTED_MODEL), null) != null) {
            Gson gson = new Gson();
            MODELS = gson.fromJson(
                    pref.getString("COMPARITION_" + storePreference.getStringValue(GlobalData.SELECTED_MODEL), null),
                    new TypeToken<ComparisonDataModel>() {
                    }.getType());

            Glide.with(getActivity()).load(MODELS
                    .getComparisonModelList().getModelImageUrl().trim()).into(productImage);
            ADAPTER = new ComparisionExpandableListAdapter(getActivity(), MODELS.getComparisonCategoryList());
            cpMainList.setAdapter(ADAPTER);
            setItemLayout();
        } else {
            lloutWhole.setVisibility(View.GONE);
            imgNoData.setVisibility(View.VISIBLE);
        }
    }

    @SuppressLint("ClickableViewAccessibility")
    private void setItemLayout() {
        itemLayout.removeAllViews();
        childLayout.removeAllViews();
        if (MODELS.getCompareModel().size() > 0) {
            expandButton.setVisibility(View.VISIBLE);
            for (int i = 0; i < MODELS.getCompareModel().size(); i++) {
                View view = LayoutInflater.from(getActivity()).inflate(R.layout.comparison_button_layout, null);
                LinearLayout linearLayout1 = (LinearLayout) view.findViewById(R.id.lineardrag);
                final ImageView imageView = view.findViewById(R.id.image);
                final TextView textView = view.findViewById(R.id.textButton);
                view.setId(i);
                imageView.setId(i);
                textView.setId(i);
                linearLayout1.setId(i);
                linearLayout1.setTag(i + "");
                view.setTag(i);
//            view.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    addChildList((Integer) v.getTag());
//                }
//            });

                linearLayout1.setOnTouchListener(new View.OnTouchListener() {
                    @Override
                    public boolean onTouch(View v, MotionEvent event) {
                        clickId = v.getId();
                        LinearLayout v1 = (LinearLayout) itemLayout.getChildAt(clickId);
                        LinearLayout Linear1 = (LinearLayout) v1.getChildAt(0);
                        linearplacedrop.setVisibility(View.VISIBLE);
                        ClipData data = ClipData.newPlainText("", "");
                        View.DragShadowBuilder shadow = new View.DragShadowBuilder(Linear1);
                        v.startDrag(data, shadow, null, 0);
                        return false;
                    }

                });
                textView.setText(MODELS.getCompareModel().get(i).getModel().getModelName());
                Glide.with(getActivity()).load(MODELS.getCompareModel().get(i).getModel().getModelImageUrl().trim()).into(imageView);
                itemLayout.addView(view);
            }
        } else {
            expandButton.setVisibility(View.GONE);
        }
    }

    @SuppressLint("ClickableViewAccessibility")
    private void addChildList(int pos) {
        try {
            for (int i = 0; i < childLayout.getChildCount(); i++) {
                layout = (LinearLayout) childLayout.getChildAt(i);
                ExpandableListView listView;
                if (layout != null) {
                    listView = (ExpandableListView) layout.getChildAt(1);
                    if (listView != null)
                        for (int j = 0; j < MODELS.getCompareModel().size(); j++)
                            listView.collapseGroup(j);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        View view = LayoutInflater.from(getActivity()).inflate(R.layout.activity_comparision_child, null);
        ImageView imageView = view.findViewById(R.id.productChildImage);
        TextView textView = view.findViewById(R.id.productChildName);
        ExpandableListView cpChildList = view.findViewById(R.id.cpChildList);
        ImageButton closeButton = view.findViewById(R.id.closeButton);

        cpChildList.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {

            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                View v = view.getChildAt(0);
                if (v != null)
                    cpMainList.setSelectionFromTop(firstVisibleItem, v.getTop());
            }
        });
        closeButton.setTag(view);
        closeButton.setId(pos);
        closeButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                for (int j = 0; j < itemLayout.getChildCount(); j++) {
                    if (v.getId() == j) {
                        LinearLayout v1 = (LinearLayout) itemLayout.getChildAt(j);
                        LinearLayout linear = (LinearLayout) v1.getChildAt(0);
                        ImageView text = (ImageView) linear.getChildAt(0);
                        TextView textView = (TextView) linear.getChildAt(1);
                        linear.setBackgroundColor(Color.parseColor("#10000000"));
                        text.setAlpha(1f);
                        textView.setAlpha(1f);
                        linear.setEnabled(true);
                        childLayout.removeView((View) v.getTag());
                        if (childLayout.getChildCount() == 0) {
                            linearplacedrop.setVisibility(View.VISIBLE);
                        }
                    }
                }
            }
        });
        textView.setText(MODELS.getCompareModel().get(pos).getModel().getModelName());
        Glide.with(getActivity()).load(MODELS.getCompareModel().get(pos).getModel().getModelImageUrl().trim()).into(imageView);
        cpChildList.setAdapter(new ComparisionChildAdapter(getActivity(), MODELS.getCompareModel().get(pos).getCategory(), MODELS.getComparisonCategoryList()));
        cpChildList.setTag(pos);

        cpChildList.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
            @Override
            public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
                if (cpMainList.isGroupExpanded(groupPosition)) {
                    cpMainList.collapseGroup(groupPosition);
                } else {
                    cpMainList.expandGroup(groupPosition);
                }

                for (int i = 0; i < childLayout.getChildCount(); i++) {
                    LinearLayout layout = (LinearLayout) childLayout.getChildAt(i);
                    ExpandableListView listView = (ExpandableListView) layout.getChildAt(1);
                    if (((int) parent.getTag()) != ((int) listView.getTag())) {
                        if (listView.isGroupExpanded(groupPosition)) {
                            listView.collapseGroup(groupPosition);
                        } else {
                            listView.expandGroup(groupPosition);
                        }
                    }

                }
                return false;
            }
        });

        DisplayMetrics displayMetrics = new DisplayMetrics();
        Objects.requireNonNull(getActivity()).getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        int width = displayMetrics.widthPixels;
        LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        param.width = Double.valueOf((width / 2) * 0.8).intValue();
        linearplacedrop.setVisibility(View.GONE);
        childLayout.addView(view, param);
    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {

    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
        View v = view.getChildAt(0);
        if (v != null) {
            for (int i = 0; i < childLayout.getChildCount(); i++) {
                layout = (LinearLayout) childLayout.getChildAt(i);
                ExpandableListView listView;
                if (layout != null) {
                    listView = (ExpandableListView) layout.getChildAt(1);
                    if (listView != null)
                        listView.setSelectionFromTop(firstVisibleItem, v.getTop());
                }
            }
        }
    }

    @Override
    public void onExpansionUpdate(float expansionFraction, int state) {
        Log.d("ExpandableLayout", "State: " + state);
        expandButton.setRotation(expansionFraction * 0);
    }

    @Override
    public void onClick(View view) {
        expandableLayout.toggle();
        if (isOpened) {
            expandButton.setImageResource(R.drawable.leftcompare);
            isOpened = false;
        } else {
            expandButton.setImageResource(R.drawable.rightcompare);
            isOpened = true;
        }
    }
}
