package org.keyscience.fragments;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import org.keyscience.R;
import org.keyscience.adapters.AccordionListAdapter;
import org.keyscience.app.Constants;
import org.keyscience.app.HomeActivity;

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

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

public class KeyChallengeFragment extends Fragment {

    ExpandableListView expandableListView;
    private Context context;

    private Button prevWinnersButton;
    private Button miniChallenge2Button;
    private ImageView preziButton;
    private Button keyRegistrationButton;

    private List<String> parentItems;
    private Map<String, List<String>> childItems;
    HashMap<String, Integer> fragmentMap = new HashMap<>();

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable final Bundle savedInstanceState) {

        context = getContext();

        View view = inflater.inflate(R.layout.keychallenge_fragment, container, false);

        // Paragraphs that require HTML
        String kcParagraph3 = getResources().getString(R.string.kcParagraph3);
        TextView txtParagraph3 = view.findViewById(R.id.textView7);
        txtParagraph3.setText(Html.fromHtml(kcParagraph3));

        AddChildActivities();

        expandableListView = view.findViewById(R.id.keychallenge_accordions);
        fillData();

        ExpandableListAdapter expandableListAdapter = new AccordionListAdapter(context, parentItems, childItems) {
        };
        expandableListView.setAdapter(expandableListAdapter);

        // -- We want to adjust the height of the ScrollView based on the groups children
        expandableListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {

            @Override
            public boolean onGroupClick(ExpandableListView parent, View v,
                                        int groupPosition, long id) {
                setListViewHeight(parent, groupPosition);
                return false;
            }

            private void setListViewHeight(ExpandableListView listView,
                                           int group) {
                AccordionListAdapter listAdapter = (AccordionListAdapter) listView.getExpandableListAdapter();
                int totalHeight = 0;
                int desiredWidth = View.MeasureSpec.makeMeasureSpec(listView.getWidth(),
                        View.MeasureSpec.EXACTLY);
                for (int i = 0; i < listAdapter.getGroupCount(); i++) {
                    View groupItem = listAdapter.getGroupView(i, false, null, listView);
                    groupItem.measure(desiredWidth, View.MeasureSpec.UNSPECIFIED);

                    totalHeight += groupItem.getMeasuredHeight();

                    if (((listView.isGroupExpanded(i)) && (i != group))
                            || ((!listView.isGroupExpanded(i)) && (i == group))) {
                        for (int j = 0; j < listAdapter.getChildrenCount(i); j++) {
                            View listItem = listAdapter.getChildView(i, j, false, null,
                                    listView);
                            listItem.measure(desiredWidth, View.MeasureSpec.UNSPECIFIED);

                            totalHeight += listItem.getMeasuredHeight();

                        }
                    }
                }

                ViewGroup.LayoutParams params = listView.getLayoutParams();
                int height = totalHeight
                        + (listView.getDividerHeight() * (listAdapter.getGroupCount() - 1));
                if (height < 10)
                    height = 300;
                params.height = height;
                listView.setLayoutParams(params);
                listView.requestLayout();
            }
        });
        //

        initButtons(view);

        return view;
    }

    public void openBrochure(View view) {
        Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://issuu.com/kbcf/docs/kc-2017-brochure-final-web"));
        startActivity(browserIntent);
    }

    public void openRegistrationUrl(View view) {
        Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.keyscience.org/projects/key-challenge/"));
        startActivity(browserIntent);
    }

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

    public void initButtons(View view) {
        prevWinnersButton = view.findViewById(R.id.prevwinners_button);
        prevWinnersButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ((HomeActivity) context).setViewPager(fragmentMap.get(Constants.KEY_CHALLENGE_WINNERS));
                Toast.makeText(context, "Previous Winners", Toast.LENGTH_SHORT).show();
            }
        });

        miniChallenge2Button = view.findViewById(R.id.minichallenge2_button);
        miniChallenge2Button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ((HomeActivity) context).setViewPager(fragmentMap.get(Constants.MINI_CHALLENGE));
                Toast.makeText(context, "Mini Challenge", Toast.LENGTH_SHORT).show();
            }
        });

        preziButton = view.findViewById(R.id.key_challenge_prezi);
        preziButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openBrochure(v);
            }
        });

        keyRegistrationButton = view.findViewById(R.id.keychallenge_reg_button);
        keyRegistrationButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openRegistrationUrl(v);
            }
        });
    }

    public void fillData() {
        parentItems = new ArrayList<>();
        childItems = new HashMap<>();

        String[] parentList = new String[]{"Pre K - 1st Grades",
                "2nd - 3rd Grades",
                "4th - 5th Grades",
                "6th - 8th Grades",
                "9th - 10th Grades",
                "11th - 12th Grades",
                "At-Home"};
        parentItems.addAll(Arrays.asList(parentList));

        String preK_content = getResources().getString(R.string.PreK);
        String second_third_content = getResources().getString(R.string.secondThirdGrades);
        String fourth_fifth_content = getResources().getString(R.string.fourthFifthGrades);
        String sixth_eight_content = getResources().getString(R.string.sixthEightGrades);
        String ninth_tenth_content = getResources().getString(R.string.ninthTenthGrades);
        String eleventh_twelfth_content = getResources().getString(R.string.eleventhTwelfthGrades);
        String at_home_content = getResources().getString(R.string.atHome);

        List<String> preK_first = new ArrayList<>();
        preK_first.add(preK_content);

        List<String> second_third = new ArrayList<>();
        second_third.add(second_third_content);

        List<String> fourth_fifth = new ArrayList<>();
        fourth_fifth.add(fourth_fifth_content);

        List<String> sixth_eight = new ArrayList<>();
        sixth_eight.add(sixth_eight_content);

        List<String> ninth_tenth = new ArrayList<>();
        ninth_tenth.add(ninth_tenth_content);

        List<String> eleventh_twelfth = new ArrayList<>();
        eleventh_twelfth.add(eleventh_twelfth_content);

        List<String> at_home = new ArrayList<>();
        at_home.add(at_home_content);


        childItems.put(parentItems.get(0), preK_first);
        childItems.put(parentItems.get(1), second_third);
        childItems.put(parentItems.get(2), fourth_fifth);
        childItems.put(parentItems.get(3), sixth_eight);
        childItems.put(parentItems.get(4), ninth_tenth);
        childItems.put(parentItems.get(5), eleventh_twelfth);
        childItems.put(parentItems.get(6), at_home);
    }
}
