package org.keyscience.adapters;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.support.v4.widget.DrawerLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.TextView;

import org.keyscience.R;
import org.keyscience.SingletonPattern.User;
import org.keyscience.app.Constants;
import org.keyscience.app.ExploreTheKey;
import org.keyscience.app.HomeActivity;
import org.keyscience.app.ReviewMapActivity;
import org.keyscience.fragments.SectionsStatePagerAdapter;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static org.keyscience.fragments.SectionsStatePagerAdapter.getInstanceSectionsStatePagerAdapter;

public class ExpListAdapter extends BaseExpandableListAdapter {

    Context context;
    List<String> parentItems;
    Map<String, List<String>> childItems;

    HashMap<String, Integer> itemImageRes = new HashMap<>();
    HashMap<String, Integer> itemImageRes_Active = new HashMap<>();

    public static HashMap<String, Integer> getFragmentMap() {
        return fragmentMap;
    }

    static HashMap<String, Integer> fragmentMap = new HashMap<>();

    private DrawerLayout drawerLayout;

    private static final int[] EMPTY_STATE_SET = {};
    private static final int[] GROUP_EXPANDED_STATE_SET =
            {android.R.attr.state_expanded};
    private static final int[][] GROUP_STATE_SETS = {
            EMPTY_STATE_SET, // 0
            GROUP_EXPANDED_STATE_SET // 1
    };

    public ExpListAdapter(Context context, List<String> parentItems, Map<String, List<String>> childItems) {
        this.context = context;
        this.parentItems = parentItems;
        this.childItems = childItems;

        AddParentIcons();
        AddChildIcons();

        AddChildActivities();
    }

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

    @Override
    public int getChildrenCount(int i) {
        return childItems.get(parentItems.get(i)).size();
    }

    @Override
    public Object getGroup(int i) {
        return parentItems.get(i);
    }

    @Override
    public Object getChild(int i, int i1) {
        return childItems.get(parentItems.get(i)).get(i1);
    }

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

    @Override
    public long getChildId(int i, int i1) {
        return i1;
    }

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

    @Override
    public View getGroupView(final int i, final boolean b, View view, final ViewGroup viewGroup) {
        final String parent = (String) getGroup(i);

        //TODO: Find a way to refresh this each time on open (Like child, with the collapseGroup stuff)

        if (view == null) {
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
            view = inflater.inflate(R.layout.list_parent, null);
        }

        final ImageView iconParent = view.findViewById(R.id.navDrawerItemIcon);

        // Parent Icons set by name of group
        if (itemImageRes.containsKey(parent))
            if (b)
                iconParent.setImageResource(itemImageRes_Active.get(parent));
            else {
                int fragmentId = HomeActivity.viewPager.getCurrentItem();
                final String currentFragment = getInstanceSectionsStatePagerAdapter().getFragmentName(fragmentId);

                if (parent.equals("Home") || parent.equals("Profile") || parent.equals("News") || parent.equals("Events")) // Home
                {
                    if (currentFragment.equals(parent))
                        iconParent.setImageResource(itemImageRes_Active.get(parent));
                    else
                        iconParent.setImageResource(itemImageRes.get(parent));
                } else
                    iconParent.setImageResource(itemImageRes.get(parent));

            }

        TextView txtParent = view.findViewById(R.id.txtParent);
        txtParent.setText(parent);

        View ind = view.findViewById(R.id.explist_indicator);

        if (ind != null) {
            ImageView indicator = (ImageView) ind;
            if (getChildrenCount(i) == 0) {
                indicator.setVisibility(View.INVISIBLE);
            } else {
                indicator.setVisibility(View.VISIBLE);
                int stateSetIndex = (b ? 1 : 0);
                Drawable drawable = indicator.getDrawable();
                drawable.setState(GROUP_STATE_SETS[stateSetIndex]);
            }
        }

        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (parent.equals(Constants.HOME) | parent.equals(Constants.LOGIN) | parent.equals(Constants.EVENTS) | parent.equals(Constants.NEWS)) {
                    //    Toast.makeText(context, parent, Toast.LENGTH_SHORT).show();

                    if (parent.equals(Constants.HOME)) {
                        ((HomeActivity) context).setViewPager(fragmentMap.get(Constants.HOME));
                    } else if (parent.equals(Constants.LOGIN)) {

                        // if user already logged in
                        if (User.getInstance() != null) {
                            ((HomeActivity) context).setViewPager(fragmentMap.get(Constants.PROFILE));
                        } else {
                            ((HomeActivity) context).setViewPager(fragmentMap.get(Constants.LOGIN));

                        }

                    } else if (parent.equals(Constants.EVENTS)) {
                        ((HomeActivity) context).setViewPager(fragmentMap.get(Constants.EVENTS));
                    } else if (parent.equals(Constants.NEWS)) {
                        ((HomeActivity) context).setViewPager(fragmentMap.get(Constants.NEWS));
                    }

                    CloseNavDrawer();
                    //CollapseExpandGroup(i, viewGroup);
                } else {
                    if (b)
                        ((ExpandableListView) viewGroup).collapseGroup(i);
                    else
                        ((ExpandableListView) viewGroup).expandGroup(i, true);
                }
            }
        });

        return view;
    }

    @Override
    public View getChildView(final int i, final int i1, final boolean b, View view, final ViewGroup viewGroup) {
        final String child = (String) getChild(i, i1);

        //CollapseExpandGroup(i, viewGroup);

        if (view == null) {
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
            view = inflater.inflate(R.layout.list_child, null);
        }

        final ImageView iconChild = view.findViewById(R.id.navDrawerChildItemIcon);

        // Child Icons set by name of child
        int fragmentId = HomeActivity.viewPager.getCurrentItem();
        final String currentFragment = getInstanceSectionsStatePagerAdapter().getFragmentName(fragmentId);

        if (itemImageRes.containsKey(child)) {
            if (currentFragment.equals(child)) {
                iconChild.setImageResource(itemImageRes_Active.get(child));
            } else
                iconChild.setImageResource(itemImageRes.get(child));
        }

        TextView txtChild = view.findViewById(R.id.txtChild);
        txtChild.setText(child);

        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 'Child' Fragments
                if (fragmentMap.containsKey(child)) {
//                    Intent intent = new Intent(context, activityMap.get(child));
//                    context.startActivity(intent);

                    // since Explore the Key is an activity, not a fragment, check
                    // if selected, otherwise set the fragment to corresponding item
                    if (child.equals(Constants.CSP_EXPLORE)) {
                        Intent intent = new Intent(context, ExploreTheKey.class);
                        context.startActivity(intent);
                    } else if (child.equals(Constants.CSP_REVIEW)) {
                        Intent intent = new Intent(context, ReviewMapActivity.class);
                        context.startActivity(intent);
                    } else {
                        ((HomeActivity) context).setViewPager(fragmentMap.get(child));
                    }


                    CloseNavDrawer();

                    //    CollapseExpandGroup(i, viewGroup);

//                    Toast.makeText(context, child, Toast.LENGTH_SHORT).show();
                }
            }
        });

        return view;
    }

    // Hacky way of resetting the viewGroup so that the icon update can reflect.
//    public void CollapseExpandGroup(int i, ViewGroup viewGroup) {
//        ((ExpandableListView) viewGroup).collapseGroup(i);
//        ((ExpandableListView) viewGroup).expandGroup(i);
//    }

    public void CloseNavDrawer() {
        drawerLayout = ((HomeActivity) context).findViewById(R.id.drawer_layout);
        drawerLayout.closeDrawers();
    }

    @Override
    public boolean isChildSelectable(int i, int i1) {
        return true;
    }

    public void AddParentIcons() {
        itemImageRes.put(Constants.HOME, R.drawable.home);
        itemImageRes.put(Constants.LOGIN, R.drawable.profile);
        itemImageRes.put(Constants.CSP_LAB, R.drawable.review);
        itemImageRes.put(Constants.PROGRAMS, R.drawable.programs);
        // Events & News

        itemImageRes.put(Constants.RESOURCES, R.drawable.resources);

        // Active Images
        itemImageRes_Active.put(Constants.HOME, R.drawable.home_a);
        itemImageRes_Active.put(Constants.LOGIN, R.drawable.profile_a);
        itemImageRes_Active.put(Constants.CSP_LAB, R.drawable.review_a);
        itemImageRes_Active.put(Constants.PROGRAMS, R.drawable.programs_a);
        itemImageRes_Active.put(Constants.RESOURCES, R.drawable.resources_a);
    }

    public void AddChildIcons() {

        // 'CSP Lab'
        itemImageRes.put(Constants.CSP_LEARN, R.drawable.learn);
        itemImageRes.put(Constants.CSP_EXPLORE, R.drawable.explore);
        itemImageRes.put(Constants.CSP_RECORD, R.drawable.record);
        itemImageRes.put(Constants.CSP_REVIEW, R.drawable.review);

        // 'Programs'
        itemImageRes.put(Constants.KEY_CHALLENGE, R.drawable.keychallenge);
        itemImageRes.put(Constants.WATER_QUALITY, R.drawable.water_quality);
        itemImageRes.put(Constants.SEA_LEVEL_RISE, R.drawable.sealevel);
        itemImageRes.put(Constants.WATER_WATCH, R.drawable.waterwatch);
        itemImageRes.put(Constants.REEF_RESTORATION, R.drawable.reefrestoration);
        itemImageRes.put(Constants.LECTURE_SERIES, R.drawable.lectures);
        itemImageRes.put(Constants.FIELD_ACTIVITIES, R.drawable.fieldactivities);

        // 'Resources'
        itemImageRes.put(Constants.ABOUT_US, R.drawable.about);
        itemImageRes.put(Constants.OUR_BIOMES, R.drawable.biomes);
        itemImageRes.put(Constants.NEWSLETTERS, R.drawable.news);
        itemImageRes.put(Constants.OUR_PARTNERS, R.drawable.partners);
        itemImageRes.put(Constants.CONTACT_US, R.drawable.contact);

        itemImageRes.put(Constants.EVENTS, R.drawable.events);
        itemImageRes.put(Constants.NEWS, R.drawable.news);

        // Active Images
        // 'CSP Lab'
        itemImageRes_Active.put(Constants.CSP_LEARN, R.drawable.learn_a);
        itemImageRes_Active.put(Constants.CSP_EXPLORE, R.drawable.explore_a);
        itemImageRes_Active.put(Constants.CSP_RECORD, R.drawable.record_a);
        itemImageRes_Active.put(Constants.CSP_REVIEW, R.drawable.review_a);

        // 'Programs'
        itemImageRes_Active.put(Constants.KEY_CHALLENGE, R.drawable.keychallenge_a);
        itemImageRes_Active.put(Constants.WATER_QUALITY, R.drawable.water_quality_a);
        itemImageRes_Active.put(Constants.SEA_LEVEL_RISE, R.drawable.sealevel_a);
        itemImageRes_Active.put(Constants.WATER_WATCH, R.drawable.waterwatch_a);
        itemImageRes_Active.put(Constants.REEF_RESTORATION, R.drawable.reefrestoration_a);
        itemImageRes_Active.put(Constants.LECTURE_SERIES, R.drawable.lectures_a);
        itemImageRes_Active.put(Constants.FIELD_ACTIVITIES, R.drawable.fieldactivities_a);

        // 'Resources'
        itemImageRes_Active.put(Constants.ABOUT_US, R.drawable.about_a);
        itemImageRes_Active.put(Constants.OUR_BIOMES, R.drawable.biomes_a);
        itemImageRes_Active.put(Constants.NEWSLETTERS, R.drawable.news_a);
        itemImageRes_Active.put(Constants.OUR_PARTNERS, R.drawable.partners_a);
        itemImageRes_Active.put(Constants.CONTACT_US, R.drawable.contact_a);

        itemImageRes_Active.put(Constants.EVENTS, R.drawable.events_a);
        itemImageRes_Active.put(Constants.NEWS, R.drawable.news_a);
    }

    public void AddChildActivities() {
        SectionsStatePagerAdapter sectionsStatePagerAdapter = getInstanceSectionsStatePagerAdapter();
        for (int i = 0; i < sectionsStatePagerAdapter.getCount(); i++) {
            fragmentMap.put(sectionsStatePagerAdapter.getFragmentName(i), i);
        }
    }
}
