package kr.co.zumo.app.lifeplus.view.fragment.faq;

import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.github.aakira.expandablelayout.ExpandableRelativeLayout;

import java.util.List;

import kr.co.zumo.app.R;
import kr.co.zumo.app.lifeplus.bean.api.FAQBean;

/**
 * FaqExpandableListViewAdapter
 * <pre>
 * </pre>
 *
 * @author 하세미
 * @version 1.0
 * @history 하세미   [2018-10-01]   [최초 작성]
 * @since 2018-10-01
 */
public class FAQExpandableListViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

  private List<FAQBean> data;

  public FAQExpandableListViewAdapter(List<FAQBean> data) {
    this.data = data;
  }

  @NonNull
  @Override
  public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    View view = LayoutInflater
      .from(parent.getContext())
      .inflate(R.layout.faq_question_list, parent, false);
    return new FAQExpandableViewHolder(view);
  }

  @Override
  public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {

    FAQBean bean = data.get(position);
    ((FAQExpandableViewHolder) holder).bind(bean);
    ((FAQExpandableViewHolder) holder).layoutAnswer.collapse();
    ((FAQExpandableViewHolder) holder).itemView.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View view) {
        boolean isExpanded = bean.isExpanded();
        bean.setExpanded(!isExpanded);
        ((FAQExpandableViewHolder) holder).changed(bean.isExpanded());
      }
    });
  }

  @Override
  public int getItemCount() {
    return data.size();
  }

  private class FAQExpandableViewHolder extends RecyclerView.ViewHolder {

    private TextView textViewCategory;
    private TextView textViewQuestion;
    private ImageView buttonArrow;
    private ExpandableRelativeLayout layoutAnswer;
    private TextView textViewAnswer;

    public FAQExpandableViewHolder(View itemView) {
      super(itemView);
      textViewCategory = itemView.findViewById(R.id.faq_category);
      textViewQuestion = itemView.findViewById(R.id.faq_question);
      buttonArrow = itemView.findViewById(R.id.button_open_arrow);
      layoutAnswer = itemView.findViewById(R.id.layout_answer);
      textViewAnswer = itemView.findViewById(R.id.faq_answer);

    }

    private void bind(FAQBean faqBean) {
      textViewAnswer.setText(faqBean.getContents());
      textViewQuestion.setText(faqBean.getTitle());
      textViewCategory.setText(faqBean.getCategory());

    }

    private void changed(boolean isExpanded) {
      layoutAnswer.toggle();
      buttonArrow.setImageResource(isExpanded ? R.drawable.icon_closearrow : R.drawable.icon_openarrow);
    }
  }
}
