package com.hikapro.backpack.presenter.adapters.helper.items;

import android.support.v4.util.LongSparseArray;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;

/**
 * Created by tariel on 30/04/16.
 */
public class HeaderViewCache implements HeaderProvider {

    private final StickyHeaderAdapter adapter;
    private final LongSparseArray<View> headerViews = new LongSparseArray<>();

    public HeaderViewCache(StickyHeaderAdapter adapter) {
        this.adapter = adapter;
    }

    @Override
    public View getHeader(RecyclerView parent, int position) {
        long headerId = adapter.getHeaderId(position);

        View header = headerViews.get(headerId);
        if (header == null) {
            RecyclerView.ViewHolder viewHolder = adapter.onCreateHeaderViewHolder(parent);
            adapter.onBindHeaderViewHolder(viewHolder, position);
            header = viewHolder.itemView;
            if (header.getLayoutParams() == null) {
                header.setLayoutParams(new ViewGroup.LayoutParams(
                        ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
            }

            int widthSpec;
            int heightSpec;

            widthSpec = View.MeasureSpec.makeMeasureSpec(parent.getWidth(), View.MeasureSpec.EXACTLY);
            heightSpec = View.MeasureSpec.makeMeasureSpec(parent.getHeight(), View.MeasureSpec.UNSPECIFIED);

            int childWidth = ViewGroup.getChildMeasureSpec(widthSpec,
                    parent.getPaddingLeft() + parent.getPaddingRight(), header.getLayoutParams().width);
            int childHeight = ViewGroup.getChildMeasureSpec(heightSpec,
                    parent.getPaddingTop() + parent.getPaddingBottom(), header.getLayoutParams().height);
            header.measure(childWidth, childHeight);
            header.layout(0, 0, header.getMeasuredWidth(), header.getMeasuredHeight());
            headerViews.put(headerId, header);
        }
        return header;
    }

    @Override
    public void invalidate() {
        headerViews.clear();
    }
}
