/*
 * Copyright (c) 2015. Ncomz. All Rights Reserved
 */

package com.ntels.onecable.admin.view.install;

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

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

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

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

    public static final int TYPE_HEADER = 0;
    public static final int TYPE_ITEM = 1;
    public static final int TYPE_FOOTER = 2;

    private ListInterface adapterCallback;
    private Util mUtil = new Util();
    private ArrayList<HashMap<String, Object>> alTotalList = new ArrayList<>();
    private Context mContext;
    private AppConfig mAppConfig;
    private int listLayoutHeader;
    private int listLayoutItem;
    private int listLayoutFooter;
    private int type = 0;
    private Boolean isListCheck = false;
    private Boolean isEditCheck = false;
    private Boolean isPermissionCheck = false;
    private Boolean isDelCheck = false;
    private Boolean isHeaderCheck = false;
    private Boolean isFooterCheck = false;
    private Boolean isFooterVisible = false;
    private Boolean isHomehubInstall = false;
//    private String mDeviceId = "";

    private HashMap<String, Object> mDeleteInfo;

    /**
     * 생성자.
     *
     * @param context          컨텍스트
     * @param listLayoutHeader Header layout resource id
     * @param listLayoutItem   Item layout resource id
     * @param listLayoutFooter Footer layout resource id
     * @param alTmp            RecyclerView에 보여줄 data
     * @param adapterCallback  Callback listener
     */
    public FragmentInstallAdapter(Context context, int listLayoutHeader, int listLayoutItem,
                                  int listLayoutFooter, ArrayList<HashMap<String, Object>> alTmp,
                                  ListInterface adapterCallback) {

        this.mContext = context;
        alTotalList = alTmp;
        this.listLayoutHeader = listLayoutHeader;
        this.listLayoutItem = listLayoutItem;
        this.listLayoutFooter = listLayoutFooter;
        mAppConfig = (AppConfig) this.mContext.getApplicationContext();

        try {
            this.adapterCallback = adapterCallback;
        } catch (ClassCastException ex) {
            ex.printStackTrace();
        }
    }

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

        return isListCheck;
    }

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

        isListCheck = isCheck;
    }

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

        return isEditCheck;
    }

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

        isEditCheck = isCheck;
    }

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

        return isPermissionCheck;
    }

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

        isPermissionCheck = isCheck;
    }

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

        return isDelCheck;
    }

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

        isDelCheck = isCheck;
    }

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

        return isHeaderCheck;
    }

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

        isHeaderCheck = isCheck;
    }

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

        return isFooterCheck;
    }

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

        isFooterCheck = isCheck;
    }

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

        return isFooterVisible;
    }

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

        isFooterVisible = isCheck;
    }

    /**
     * {@link #isFooterVisible} getter.
     *
     * @return true or false
     */
    public HashMap<String, Object> getDeleteInfo() {

        return mDeleteInfo;
    }

    @Override
    public int getItemCount() {

        return alTotalList.size();
    }


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

        if (viewType == TYPE_ITEM) {
            View view = LayoutInflater.from(parent.getContext()).inflate(listLayoutItem, parent, false);
            return new ItemViewHoler(view);
        } else if (viewType == TYPE_HEADER) {
            View view = LayoutInflater.from(parent.getContext()).inflate(listLayoutHeader, parent, false);
            return new HeaderViewHolder(view);
        } else if (viewType == 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");
    }

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

        try {
            HashMap<String, Object> itemMap;
            itemMap = alTotalList.get(position);
            if (holder instanceof ItemViewHoler) {
                ItemViewHoler itemViewHolerView = (ItemViewHoler) holder;

                String ctrtCnt = mUtil.null2string(itemMap.get(Constants.KEY_CTRT_CNT));
                String categoryName = mUtil.null2string(itemMap.get(Constants.KEY_CATEGORY_NAME));
                String categoryCode = mUtil.null2string(itemMap.get(Constants.KEY_CATEGORY_CODE));
                String installCnt = mUtil.null2string(itemMap.get(Constants.KEY_INSTALL_CNT));
                String deviceList = mUtil.null2string(itemMap.get(Constants.KEY_DEVICE_LIST));
                String deviceTypeId = mUtil.null2string(itemMap.get(Constants.KEY_DEVICE_TYPE_ID));
//                String editYn = mUtil.null2string(itemMap.get(Constants.KEY_EDIT_YN));
                String displayYn = mUtil.null2string(itemMap.get(Constants.KEY_DISPLAY_YN));

                Boolean isGateWay = false;
                if (deviceTypeId.equals(Constants.DEVICE_TYPE_ID_GATEWAY)) {
                    isGateWay = true;

                    if (installCnt.equals("0")) {
                        isHomehubInstall = false;
                    } else {
                        isHomehubInstall = true;
                    }
                }

                itemViewHolerView.tvRowBody_Ctrt.setText(ctrtCnt);
                itemViewHolerView.tvRowBody_Title.setText(categoryName);
                itemViewHolerView.tvRowBody_Install.setText(installCnt);

//                if (editYn.equals("Y")){
                if (isEditCheck) {
                    itemViewHolerView.btnRowBody_Add.setVisibility(View.VISIBLE);

                    Boolean isEnable = false;

                    if (isGateWay && !isHomehubInstall) {
                        isEnable = true;
                    } else if (!isGateWay
                            && isHomehubInstall
                            && (mUtil.str2int(ctrtCnt) > mUtil.str2int(installCnt))) {
                        isEnable = true;
                    }

                    // 계약 <= 설치
                    if (!isEnable) {
                        itemViewHolerView.btnRowBody_Add.setEnabled(false);
                        itemViewHolerView.btnRowBody_Add.setOnClickListener(null);
                    } else {
                        // 계약 > 설치
                        itemViewHolerView.btnRowBody_Add.setEnabled(true);
                        itemViewHolerView.btnRowBody_Add.setTag(position);
                        itemViewHolerView.btnRowBody_Add.setOnClickListener(new View.OnClickListener() {
                            int tag = 0;

                            @Override
                            public void onClick(View view) {
                                tag = (int) view.getTag();
                                adapterCallback.onCallAction(0, tag);
                            }
                        });
                    }
                } else {
                    itemViewHolerView.btnRowBody_Add.setVisibility(View.GONE);
                    itemViewHolerView.btnRowBody_Add.setOnClickListener(null);

                }

                itemViewHolerView.llRowBody_Contents.setVisibility(View.GONE);
//                itemViewHolerView.tvRowBody_Icon.setBackgroundResource(R.drawable.common_list_icon_arrow_up);
                if (!deviceList.equals("")) {

                    itemViewHolerView.llRowBody_Contents.removeAllViews();

                    ArrayList<HashMap<String, Object>> alDeviceList = (ArrayList<HashMap<String, Object>>) itemMap.get(Constants
                            .KEY_DEVICE_LIST);

                    if (alDeviceList.size() > 0) {

                        if (deviceTypeId.equals(Constants.DEVICE_TYPE_ID_GATEWAY)) {
                            AppConfig.getInstance().setDevicesList(alDeviceList);
                        }
                        for (int row = 0; row < alDeviceList.size(); row++) {
                            HashMap<String, Object> hmDevice = new HashMap<String, Object>();
                            hmDevice = alDeviceList.get(row);
                            hmDevice.put(Constants.KEY_CATEGORY_NAME, categoryName);
                            hmDevice.put(Constants.KEY_DEVICE_TYPE_ID, deviceTypeId);

                            LinearLayout llChildView = (LinearLayout) View.inflate(mContext, R.layout.row_install_list_content, null);

                            String prdName = mUtil.null2string(hmDevice.get(Constants.KEY_PRD_NAME));
                            String prdUserName = mUtil.null2string(hmDevice.get(Constants.KEY_PRD_USER_NAME));
                            String createDatetime = mUtil.UTCtoLocal5(mUtil.null2string(hmDevice.get(Constants.KEY_CREATE_DATETIME)));
                            String deviceName = !prdUserName.equals("") ? prdUserName : prdName;

                            ((TextView) llChildView.findViewById(R.id.tvRowBody_Title)).setText(deviceName);

                            ((TextView) llChildView.findViewById(R.id.tvRowBody_DateTime)).setText(createDatetime);
                            if (isEditCheck) {
                                ((Button) llChildView.findViewById(R.id.btnRowBody_Del)).setVisibility(View.VISIBLE);
                            } else {
                                ((Button) llChildView.findViewById(R.id.btnRowBody_Del)).setVisibility(View.GONE);
                            }
                            ((Button) llChildView.findViewById(R.id.btnRowBody_Del)).setTag(hmDevice);
                            ((Button) llChildView.findViewById(R.id.btnRowBody_Del)).setOnClickListener(new View.OnClickListener() {
                                int tag = 0;

                                @Override
                                public void onClick(View view) {
                                    mDeleteInfo = (HashMap<String, Object>) view.getTag();


                                    adapterCallback.onCallAction(2, 0);

                                }
                            });
                            itemViewHolerView.llRowBody_Contents.addView(llChildView);
                        }

                        if (displayYn.equals("Y")) {
                            itemViewHolerView.llRowBody_Contents.setVisibility(View.VISIBLE);
//                            itemViewHolerView.tvRowBody_Icon.setBackgroundResource(R.drawable.common_list_icon_arrow_down);
                        }

                        Dlog.v("jino onclick");
                        itemViewHolerView.llRowBody_Title.setTag(position);
                        itemViewHolerView.llRowBody_Title.setOnClickListener(new View.OnClickListener() {
                            int tag = 0;

                            @Override
                            public void onClick(View view) {
                                tag = (int) view.getTag();

                                String displayYn = mUtil.null2string(alTotalList.get(tag).get(Constants.KEY_DISPLAY_YN));
                                if (displayYn.equals("Y")) {
                                    alTotalList.get(tag).put(Constants.KEY_DISPLAY_YN, "N");
                                } else {
                                    alTotalList.get(tag).put(Constants.KEY_DISPLAY_YN, "Y");
                                }
                                notifyDataSetChanged();
                            }
                        });


                    }

                }


            } else if (holder instanceof FooterViewHolder) {

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

                HeaderViewHolder vhItemView = (HeaderViewHolder) holder;
                vhItemView.btnHeaderRefresh.setTag(position);
                vhItemView.btnHeaderRefresh.setOnClickListener(new View.OnClickListener() {
                    int tag = 0;

                    @Override
                    public void onClick(View view) {
                        tag = (int) view.getTag();

                        adapterCallback.onListReload();
                    }
                });
            }
            holder.itemView.setTag(itemMap);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    @Override
    public int getItemViewType(int position) {
        if (getHeaderCheck() && position == 0) {
            return TYPE_HEADER;
        } else if (getFooterCheck() && position == getItemCount() - 1) {
            return TYPE_FOOTER;
        } else {
            return TYPE_ITEM;
        }
    }

    /**
     * <pre>
     * 1. ClassName :   ItemViewHoler
     * 2. FileName  :   FragmentInstallAdapter.java
     * 3. Package   :   com.ntels.onecable.view.homemember
     * 4. Date      :   2016-12-01
     * 5. Author    :   aaron
     * 6. Comment   :   Initialize
     * </pre>
     */
    public static class ItemViewHoler extends RecyclerView.ViewHolder {

        public LinearLayout llRowRoot;
        public LinearLayout llRowBody;
        public LinearLayout llRowBody_Title;
        public TextView tvRowBody_Title;
//        public ImageView tvRowBody_Icon;
        public TextView tvRowBody_Install;
        public TextView tvRowBody_Ctrt;
        public Button btnRowBody_Add;
        public LinearLayout llRowBody_Contents;

        /**
         * 생성자.
         *
         * @param itemView Item layout view
         */
        public ItemViewHoler(View itemView) {

            super(itemView);
            llRowRoot = (LinearLayout) itemView.findViewById(R.id.llRowRoot);
            llRowBody = (LinearLayout) itemView.findViewById(R.id.llRowBody);
            llRowBody_Title = (LinearLayout) itemView.findViewById(R.id.llRowBody_Title);
            tvRowBody_Title = (TextView) itemView.findViewById(R.id.tvRowBody_Title);
//            tvRowBody_Icon = (ImageView) itemView.findViewById(R.id.tvRowBody_Icon);
            tvRowBody_Install = (TextView) itemView.findViewById(R.id.tvRowBody_Install);
            tvRowBody_Ctrt = (TextView) itemView.findViewById(R.id.tvRowBody_Ctrt);
            btnRowBody_Add = (Button) itemView.findViewById(R.id.btnRowBody_Add);
            llRowBody_Contents = (LinearLayout) itemView.findViewById(R.id.llRowBody_Contents);
        }
    }

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

        public LinearLayout llRowRoot;
        public LinearLayout llRowBody;
        public TextView tvTitle;
        public Button btnHeaderRefresh;

        /**
         * 생성자.
         *
         * @param itemView Header layout view
         */
        public HeaderViewHolder(View itemView) {

            super(itemView);

            btnHeaderRefresh = (Button) itemView.findViewById(R.id.btnHeaderRefresh);
        }
    }

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

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

        /**
         * 생성자.
         *
         * @param itemView Footer layout view
         */
        public FooterViewHolder(View itemView) {

            super(itemView);

            llFooterProgress = (LinearLayout) itemView.findViewById(R.id.llFooterProgress);
            llFooterRoot = (LinearLayout) itemView.findViewById(R.id.llFooterRoot);
            llFooterBody = (LinearLayout) itemView.findViewById(R.id.llFooterBody);
            ivFooterAdd = (ImageView) itemView.findViewById(R.id.ivFooterAdd);
        }
    }
}
