package hr.fer.labust.diverapp.adapter;

import android.content.Context;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.GradientDrawable;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.StyleSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.HashMap;

import hr.fer.labust.diverapp.R;
import hr.fer.labust.diverapp.agent.Agent;
import hr.fer.labust.diverapp.agent.AgentList;
import hr.fer.labust.diverapp.agent.Attribute;

public class MainListAdapter extends BaseExpandableListAdapter{
    private final AgentList mAgentList = AgentList.getInstace();
    private final HashMap<String, Entry> mSecondLevelViews;
    private final LayoutInflater mInflater;
    private final Context mContext;

    private class Entry {
        public final CustomExpandableListView celv;
        public final SecondLevelAdapter sla;

        Entry(Agent agent) {
            celv = new CustomExpandableListView(mContext);
            sla = new SecondLevelAdapter(agent, mInflater, mContext);
            celv.setAdapter(sla);
        }
    }

    private class ViewHolder {
        TextView title;

        ViewHolder (TextView v) {
            title = v;
        }
    }

    public MainListAdapter(Context context) {
        mSecondLevelViews = new HashMap<>();
        mContext = context;

        mInflater = LayoutInflater.from(mContext);
    }

    public void expandAll(int groupPosition) {
        String name = mAgentList.getAgent(groupPosition).getName();
        CustomExpandableListView celv = mSecondLevelViews.get(name).celv;

        int n = celv.getExpandableListAdapter().getGroupCount();
        for (int i=0; i<n; i++) {
            celv.expandGroup(i);
        }
    }

    @Override
    public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
        final Agent item = (Agent)getGroup(groupPosition);
        TextView v = null;

        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.listview_element_main, null);
            v = (TextView)convertView.findViewById(R.id.mainlist_element);
            v.setTypeface(null, Typeface.BOLD);
            convertView.setTag(new ViewHolder(v));
        }
        else {
            v = ((ViewHolder)convertView.getTag()).title;
        }

        v.setText(item.getName());
        v.setTextColor(item.getColor());

        return convertView;
    }

    @Override
    public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
        String name = mAgentList.getAgent(groupPosition).getName();
        if (!mSecondLevelViews.containsKey(name)) {
            mSecondLevelViews.put(name, new Entry((Agent)getGroup(groupPosition)));
        }

        CustomExpandableListView celv = mSecondLevelViews.get(name).celv;
        int[] colors = {0, ((Agent)getGroup(groupPosition)).getColor(), 0};
        GradientDrawable gradientDrawable = new GradientDrawable(GradientDrawable.Orientation.RIGHT_LEFT, colors);
        celv.setDivider(gradientDrawable);
        celv.setChildDivider(gradientDrawable);
        celv.setDividerHeight(1);

        return celv;
    }

    @Override
    public Object getGroup(int groupPosition) {
        return mAgentList.getAgent(groupPosition);
    }



    @Override
    public int getGroupCount() {
        return mAgentList.getNumberOfAgents();
    }

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

    @Override
    public Object getChild(int groupPosition, int childPosition) {
        return mAgentList.getAgent(groupPosition);
    }

    @Override
    public int getChildrenCount(int groupPosition) {
        return 1;
    }

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

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

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

    public void update(String name) {
        if (!mAgentList.contains(name)) {
            return;
        }

        if (!mSecondLevelViews.containsKey(name)) {
            mSecondLevelViews.put(name, new Entry(mAgentList.getAgent(name)));
        }

        mSecondLevelViews.get(name).sla.notifyDataSetChanged();
    }

    public void removed(String name) {
        mSecondLevelViews.remove(name);
    }

    private class SecondLevelAdapter extends BaseExpandableListAdapter {
        private final Agent mAgent;
        private final LayoutInflater mInflater;

        SecondLevelAdapter(Agent agent, LayoutInflater inflater, Context context) {
            mAgent = agent;
            mInflater = inflater;
        }

        @Override
        public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
            TextView v = null;

            if (convertView == null) {
                convertView = mInflater.inflate(R.layout.listview_element_main, null);
                v = (TextView)convertView.findViewById(R.id.mainlist_element);
                v.setPadding(v.getPaddingLeft() + 35, v.getPaddingTop(), v.getPaddingRight(), v.getPaddingBottom());
                v.setTypeface(null, Typeface.BOLD);
                convertView.setTag(new ViewHolder(v));
            }
            else {
                v = ((ViewHolder)convertView.getTag()).title;
            }

            v.setText((String)getGroup(groupPosition));
            if (v.getText().equals("Destination")) {
                v.setTextColor(mAgent.getDestinationColor());
            }
            else {
                v.setTextColor(Color.WHITE);
            }

            return convertView;
        }

        @Override
        public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
            TextView v = null;

            if (convertView == null) {
                convertView = mInflater.inflate(R.layout.listview_element_main, null);
                v = (TextView)convertView.findViewById(R.id.mainlist_element);
                v.setPadding(v.getPaddingLeft() + 70, v.getPaddingTop(), v.getPaddingRight(), v.getPaddingBottom());
                v.setTextColor(Color.WHITE);
                convertView.setTag(new ViewHolder(v));
            }
            else {
                v = ((ViewHolder)convertView.getTag()).title;
            }

            Attribute status = (Attribute)getChild(groupPosition, childPosition);
            int nameLength = status.getName().length() + 1;
            final SpannableStringBuilder span = new SpannableStringBuilder(status.getName() + ":\n" + status.getValue());
            span.setSpan(new StyleSpan(Typeface.BOLD), 0, nameLength, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
            v.setText(span);

            return convertView;
        }

        @Override
        public Object getChild(int groupPosition, int childPosition) {
            return mAgent.getStatus(groupPosition, childPosition);
        }

        @Override
        public int getChildrenCount(int groupPosition) {
            return mAgent.getNumberOfStatsInGroup(groupPosition);
        }

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

        @Override
        public Object getGroup(int groupPosition) {
            return mAgent.getGroupName(groupPosition);
        }

        @Override
        public int getGroupCount() {
            return mAgent.getNumberOfGroupStats();
        }

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

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

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

        private class ViewHolder {
            public TextView title;

            ViewHolder(TextView v) {
                title = v;
            }
        }
    }

    private class CustomExpandableListView extends ExpandableListView {

        public CustomExpandableListView(Context context) {
            super(context);
        }

        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            heightMeasureSpec = MeasureSpec.makeMeasureSpec(2000, MeasureSpec.AT_MOST);
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        }

        @Override
        protected void onDetachedFromWindow() {
            try {
                super.onDetachedFromWindow();
            } catch (IllegalArgumentException e) {
            }
        }
    };
}
