/*
 * Copyright (c) 2016. nTels.co.,ltd. to Present.
 * All rights reserved.
 */

package com.ntels.onecable.view.rules;

import com.ntels.onecable.R;
import com.ntels.onecable.common.Constants;
import com.ntels.onecable.common.c_interface.ListInterface;
import com.ntels.onecable.common.util.Dlog;
import com.ntels.onecable.common.util.LogUtil;
import com.ntels.onecable.common.util.Util;

import android.content.Context;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
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.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

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

/**
 * <pre>
 * 1. ClassName :   RulesThingsSelectAdapter
 * 2. FileName  :   RulesThingsSelectAdapter.java
 * 3. Package   :   com.ntels.onecable.view.rules
 * 4. Date      :   2016-11-30
 * 5. Author    :   aaron
 * 6. Comment   :   Initialize
 * </pre>
 */
public class RulesThingsSelectAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

  private static final String TAG = RulesThingsSelectAdapter.class.getSimpleName();

  private ListInterface adapterCallback;

  private Util mUtil = new Util();
  public static final int TYPE_HEADER = 0;
  public static final int TYPE_ITEM = 1;
  public static final int TYPE_FOOTER = 2;
  private ArrayList<HashMap<String, Object>> alTotalList = new ArrayList<>();
  private Context context;
  private int listLayoutHeader;
  private int listLayoutItem;
  private int listLayoutFooter;
  private Boolean isListCheck = false;
  private Boolean isHeaderCheck = false;
  private Boolean isFooterCheck = false;

  /**
   * {@link #isListCheck} setter.
   *
   * @param isCheck true or false
   */
  public void setListCheck(boolean isCheck) {

    isListCheck = isCheck;
  }

  /**
   * {@link #isListCheck} getter.
   *
   * @return true or false
   */
  public boolean getListCheck() {

    return isListCheck;
  }

  /**
   * {@link #isHeaderCheck} setter.
   *
   * @param isCheck true or false
   */
  public void setHeaderCheck(boolean isCheck) {

    isHeaderCheck = isCheck;
  }

  /**
   * {@link #isHeaderCheck} getter.
   *
   * @return true or false
   */
  public boolean getHeaderCheck() {

    return isHeaderCheck;
  }

  /**
   * {@link #isFooterCheck} setter.
   *
   * @param isCheck true or false
   */
  public void setFooterCheck(boolean isCheck) {

    isFooterCheck = isCheck;
  }

  /**
   * {@link #isFooterCheck} getter.
   *
   * @return true or false
   */
  public boolean getFooterCheck() {

    return isFooterCheck;
  }

  @Override
  public int getItemCount() {

    return alTotalList.size();
  }

  /**
   * 생성자.
   *
   * @param context 컨텍스트
   * @param headerLayoutItem header layout resource id
   * @param listLayoutItem item layout resource id
   * @param footerLayoutItem footer layout resource id
   * @param alTmp adapter에 보여줄 data
   * @param adapterCallback callback object
   */
  public RulesThingsSelectAdapter(Context context, int headerLayoutItem, int listLayoutItem,
                                  int footerLayoutItem, ArrayList<HashMap<String, Object>> alTmp,
                                  ListInterface adapterCallback) {

    Dlog.v("RulesThingsSelectAdapter ");
    this.context = context;
    alTotalList = alTmp;
    listLayoutHeader = headerLayoutItem;
    this.listLayoutItem = listLayoutItem;
    listLayoutFooter = footerLayoutItem;
    try {
      this.adapterCallback = adapterCallback;
    } catch (ClassCastException ex) {
      ex.printStackTrace();
      //            throw new ClassCastException("Activity must implement AdapterCallback.");
    }
  }

  @Override
  public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

    Dlog.v("onCreateViewHolder ");
    if (viewType == TYPE_ITEM) {
      LogUtil.i(TAG, "TYPE_ITEM");
      View view = LayoutInflater.from(parent.getContext()).inflate(listLayoutItem, parent, false);
      if (view.getLayoutParams().width == RecyclerView.LayoutParams.MATCH_PARENT) {
        view.getLayoutParams().width = parent.getWidth();
      }
      return new ItemViewHolder(view);
    } else if (viewType == TYPE_HEADER) {
      LogUtil.i(TAG, "TYPE_HEADER");
      View view = LayoutInflater.from(parent.getContext()).inflate(listLayoutHeader, parent, false);
      return new HeaderViewHolder(view);
    } else if (viewType == TYPE_FOOTER) {
      LogUtil.i(TAG, "TYPE_FOOTER");
      View view = LayoutInflater.from(parent.getContext()).inflate(listLayoutFooter, parent, false);
      return new FooterViewHolder(view);
    }

    throw new RuntimeException("there is no type that matches the type " + viewType
        + " + make sure your using types correctly");
  }

  /**
   * <pre>
   * 1. ClassName :   HeaderViewHolder
   * 2. FileName  :   RulesThingsSelectAdapter.java
   * 3. Package   :   com.ntels.onecable.view.rules
   * 4. Date      :   2016-11-30
   * 5. Author    :   aaron
   * 6. Comment   :   Initialize
   * </pre>
   */
  public static class HeaderViewHolder extends RecyclerView.ViewHolder {

    /**
     * 생성자.
     *
     * @param itemView Header로 사용할 view
     */
    public HeaderViewHolder(View itemView) {

      super(itemView);

    }
  }

  /**
   * <pre>
   * 1. ClassName :   ItemViewHolder
   * 2. FileName  :   RulesThingsSelectAdapter.java
   * 3. Package   :   com.ntels.onecable.view.rules
   * 4. Date      :   2016-11-30
   * 5. Author    :   aaron
   * 6. Comment   :   Initialize
   * </pre>
   */
  public static class ItemViewHolder extends RecyclerView.ViewHolder {

    public LinearLayout llRowRoot;
    public RelativeLayout llRowBody;
    public LinearLayout llRowBodyBody;
    public TextView tvRowTitle;
    public ImageView ivRowCheck;

    /**
     * 생성자.
     *
     * @param itemView Item으로 사용할 view
     */
    public ItemViewHolder(View itemView) {

      super(itemView);
      try {
        llRowRoot = (LinearLayout) itemView.findViewById(R.id.llRowRoot);
        llRowBody = (RelativeLayout) itemView.findViewById(R.id.llRowBody);
        llRowBodyBody = (LinearLayout) itemView.findViewById(R.id.llRowBody_Body);
        tvRowTitle = (TextView) itemView.findViewById(R.id.tvRowTitle);
        ivRowCheck = (ImageView) itemView.findViewById(R.id.ivRowCheck);
      } catch (Exception ex) {
        ex.printStackTrace();
      }
    }
  }

  /**
   * <pre>
   * 1. ClassName :   FooterViewHolder
   * 2. FileName  :   RulesThingsSelectAdapter.java
   * 3. Package   :   com.ntels.onecable.view.rules
   * 4. Date      :   2016-11-30
   * 5. Author    :   aaron
   * 6. Comment   :   Initialize
   * </pre>
   */
  public static class FooterViewHolder extends RecyclerView.ViewHolder {

    public LinearLayout llFooterProgress;
    public LinearLayout llFooterRoot;
    public LinearLayout llFooterBody;
    public TextView tvFooterTitle;
    public ImageView ivFooterAdd;

    /**
     * 생성자.
     *
     * @param itemView Footer로 사용할 view
     */
    public FooterViewHolder(View itemView) {

      super(itemView);

      try {
        llFooterProgress = (LinearLayout) itemView.findViewById(R.id.llFooterProgress);
        llFooterRoot = (LinearLayout) itemView.findViewById(R.id.llFooterRoot);
        llFooterBody = (LinearLayout) itemView.findViewById(R.id.llFooterBody);
        tvFooterTitle = (TextView) itemView.findViewById(R.id.tvFooterTitle);
        ivFooterAdd = (ImageView) itemView.findViewById(R.id.ivFooterAdd);
      } catch (Exception ex) {
        ex.printStackTrace();
      }
    }
  }

  @SuppressWarnings("unchecked")
  @Override
  public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {

    Dlog.v("onBindViewHolder ");
    try {
      HashMap<String, Object> hmItem;
      hmItem = alTotalList.get(position);

      Dlog.v("jinoo", position + "");
      if (holder instanceof ItemViewHolder) {
        ItemViewHolder itemViewHolderView = (ItemViewHolder) holder;
        Dlog.v("jinoo", position + "");
        String sourceSubName = mUtil.null2string(hmItem.get(Constants.KEY_SOURCE_SUB_NAME));
        String unit = mUtil.null2string(hmItem.get(Constants.KEY_UNIT));
        String cmdclsValueList = mUtil.null2string(hmItem.get(Constants.KEY_CMDCLS_VALUE_LIST));
        String cmdclsValue = mUtil.null2string(hmItem.get(Constants.KEY_CMDCLS_VALUE));
        String conditionTypeCodeName = mUtil.null2string(
            hmItem.get(Constants.KEY_CONDITION_TYPE_CODE_NAME));
        String selectYn = mUtil.null2string(hmItem.get(Constants.KEY_SELECT_YN));
        String disableYn = mUtil.null2string(hmItem.get(Constants.KEY_DISABLE_YN));

        itemViewHolderView.tvRowTitle.setText(sourceSubName);

        itemViewHolderView.llRowBody.setTag(position);
        if (disableYn.equals("Y")) {
          itemViewHolderView.llRowBody.setEnabled(false);
          itemViewHolderView.llRowBody.setSelected(false);
        } else {
          itemViewHolderView.llRowBody.setEnabled(true);

          if (selectYn.equals("Y")) {
            itemViewHolderView.llRowBody.setSelected(true);
          } else {
            itemViewHolderView.llRowBody.setSelected(false);
          }

          itemViewHolderView.llRowBody.setTag(position);
          itemViewHolderView.llRowBody.setOnClickListener(new View.OnClickListener() {
            int tag = 0;

            @Override
            public void onClick(View view) {

              tag = (int) view.getTag();
              Dlog.v("alTotalList.size() = " + alTotalList.size());
              for (int row = 0; row < alTotalList.size(); row++) {
                alTotalList.get(row).put(Constants.KEY_SELECT_YN, "N");
              }
              alTotalList.get(tag).put(Constants.KEY_SELECT_YN, "Y");
              notifyDataSetChanged();
            }
          });
        }
        itemViewHolderView.llRowBodyBody.removeAllViews();
        // 미분류 대상THERMOSTAT_MODE, LOCK, SPEED_CONTROL, AV_CONTROL_PLAYBACK, PRESENCE, SYSTEM,
        // COLOR, METER_CURRENT, METER_TOTAL, THERMOSTAT_SETPOINT, SYSTEM
        // 분류 해야 함
        String cmdclsCode = mUtil.null2string(hmItem.get(Constants.KEY_CMDCLS_CODE));
        if (cmdclsCode.equals("SWITCH_BINARY") || cmdclsCode.equals("SENSOR_BINARY")
            || cmdclsCode.equals("VALVE") || cmdclsCode.equals("CAMERA")
            || cmdclsCode.equals("PRESENCE")) {

          if (!cmdclsValueList.equals("")) {
            ArrayList<HashMap<String, Object>> tempList;
            tempList = (ArrayList<HashMap<String, Object>>)
                hmItem.get(Constants.KEY_CMDCLS_VALUE_LIST);

            for (int row2 = 0; row2 < tempList.size(); row2++) {
              LinearLayout childView1 = (LinearLayout) View.inflate(
                  context, R.layout.row_rules_things_select_button, null);

              String optionCmdclsValue = mUtil.null2string(
                  tempList.get(row2).get(Constants.KEY_CMDCLS_VALUE));
              String optionCmdclsValueMsg = mUtil.null2string(
                  tempList.get(row2).get(Constants.KEY_CMDCLS_VALUE_MSG));

              mUtil.getTextView(childView1, R.id.tvRulesCmd).setText(optionCmdclsValueMsg);
              mUtil.getTextView(childView1, R.id.tvRulesCmd).setTag(optionCmdclsValue);
              mUtil.getView(childView1, R.id.llRulesCmd).setEnabled(false);

              if (cmdclsValue.equals(optionCmdclsValue)) {
                mUtil.getView(childView1, R.id.llRulesCmd).setSelected(true);
              } else {
                mUtil.getView(childView1, R.id.llRulesCmd).setSelected(false);
              }
              mUtil.getView(childView1, R.id.llRulesCmd).setTag(position);
              if (selectYn.equals("Y")) {
                mUtil.getView(childView1, R.id.llRulesCmd).setEnabled(true);
                mUtil.getView(childView1, R.id.llRulesCmd)
                    .setOnClickListener(new View.OnClickListener() {
                      int tag = 0;

                      @Override
                      public void onClick(View view) {

                        tag = (int) view.getTag();
                        String value = mUtil.null2string(
                            mUtil.getTextView(view, R.id.tvRulesCmd).getTag());
                        String title = mUtil.null2string(mUtil.getTextViewVal(view, R.id.tvRulesCmd));
                        Dlog.v("title = " + title);

                        alTotalList.get(tag).put(Constants.KEY_CMDCLS_VALUE, value);
                        alTotalList.get(tag).put(Constants.KEY_CMDCLS_VALUE_MSG, title);
                        alTotalList.get(tag).put(Constants.KEY_CONDITION_TYPE_CODE, "01");
                        alTotalList.get(tag).put(Constants.KEY_CONDITION_TYPE_CODE_NAME,
                            mUtil.getString(context, R.string.layout_equals));

                        notifyDataSetChanged();
                      }
                    });
              }

              itemViewHolderView.llRowBodyBody.addView(childView1);
            }
          }
        } else if (cmdclsCode.equals("SENSOR_MULTILEVEL") || cmdclsCode.equals("SWITCH_MULTILEVEL")
            || cmdclsCode.equals("METER") || cmdclsCode.equals("BATTERY")) {

          LinearLayout childView1 = (LinearLayout) View.inflate(
              context, R.layout.row_rules_things_select_value, null);
          mUtil.getTextView(childView1, R.id.tvRulesCmd)
              .setText(cmdclsValue + " " + (cmdclsValue.equals("") ? ""
                  : unit) + " " + (cmdclsValue.equals("")
                  ? ""
                  : conditionTypeCodeName));
          mUtil.getView(childView1, R.id.llRulesCmd).setEnabled(false);
          if (cmdclsValue.equals("")) {
            mUtil.getView(childView1, R.id.llRulesCmd).setSelected(false);
          } else {
            mUtil.getView(childView1, R.id.llRulesCmd).setSelected(true);
          }
          mUtil.getView(childView1, R.id.llRulesCmd).setTag(position);
          if (selectYn.equals("Y")) {
            mUtil.getView(childView1, R.id.llRulesCmd).setEnabled(true);
            mUtil.getView(childView1, R.id.llRulesCmd)
                .setOnClickListener(new View.OnClickListener() {
                  int tag = 0;

                  @Override
                  public void onClick(View view) {

                    tag = (int) view.getTag();

                    adapterCallback.onCallAction(1, tag);
                  }
                });
          }
          itemViewHolderView.llRowBodyBody.addView(childView1);
        } else if (cmdclsCode.equals("COLOR")) {

          LinearLayout childView1 = (LinearLayout) View.inflate(
                  context, R.layout.row_rules_things_select_color, null);
          if (!"".equals(cmdclsValue)) {
            Drawable drawable = context.getResources().getDrawable(R.drawable.d_rules_command);
            int selectedColor = mUtil.hsbToRgb(cmdclsValue);
            drawable.setColorFilter(selectedColor, PorterDuff.Mode.SRC);
            mUtil.getImageView(childView1, R.id.ivRulesCmd)
                    .setBackgroundDrawable(drawable);
          }
          mUtil.getView(childView1, R.id.llRulesCmd).setEnabled(false);
          mUtil.getView(childView1, R.id.llRulesCmd).setTag(position);
          if (selectYn.equals("Y")) {
            mUtil.getView(childView1, R.id.llRulesCmd).setEnabled(true);
            mUtil.getView(childView1, R.id.llRulesCmd)
                    .setOnClickListener(new View.OnClickListener() {
                      int tag = 0;

                      @Override
                      public void onClick(View view) {

                        tag = (int) view.getTag();

                        adapterCallback.onCallAction(2, tag);
                      }
                    });
          }
          itemViewHolderView.llRowBodyBody.addView(childView1);
        }

      } else if (holder instanceof HeaderViewHolder) {

        HeaderViewHolder vhItemView = (HeaderViewHolder) holder;
      } else if (holder instanceof FooterViewHolder) {

        FooterViewHolder vhItemView = (FooterViewHolder) holder;

        String moreYn = mUtil.null2string(hmItem.get(Constants.KEY_MORE_YN));

        vhItemView.llFooterBody.setVisibility(View.GONE);
        if (moreYn.equals("Y")) {
          vhItemView.llFooterProgress.setVisibility(View.VISIBLE);
          vhItemView.llFooterRoot.setVisibility(View.VISIBLE);
        } else {
          vhItemView.llFooterProgress.setVisibility(View.GONE);
          vhItemView.llFooterRoot.setVisibility(View.GONE);
        }
      }
      holder.itemView.setTag(hmItem);
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }

  private boolean isPositionHeader(int position) {

    return position == 0;
  }

  @Override
  public int getItemViewType(int position) {

    Dlog.v("getItemViewType ");
    if (getHeaderCheck() && position == 0) {
      Dlog.v("TYPE_HEADER");
      return TYPE_HEADER;
    } else if (getFooterCheck() && position == getItemCount() - 1) {
      Dlog.v("TYPE_FOOTER");
      return TYPE_FOOTER;
    } else {
      Dlog.v("TYPE_ITEM");
      return TYPE_ITEM;
    }
  }

  public ArrayList<HashMap<String, Object>> getAlhmVal() {

    return alTotalList;
  }
}
