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.OnDataSendToReslut;
import com.ntels.onecable.admin.common.http.HttpSend;
import com.ntels.onecable.admin.common.http.Response;
import com.ntels.onecable.admin.common.mdns.MdnsDiscovery;
import com.ntels.onecable.admin.common.util.Dlog;
import com.ntels.onecable.admin.common.util.LogUtil;
import com.ntels.onecable.admin.common.util.Util;
import com.ntels.onecable.admin.common.websocket.WebSocketService;
import com.ntels.onecable.admin.common.widget.CustomActivity;
import com.ntels.onecable.admin.view.dialog.CustomDialog;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

import static com.ntels.onecable.admin.common.Constants.ACT_INSTALL_HOMEHUB_REGISTER_SUCESS;
import static com.ntels.onecable.admin.common.Constants.EXTRA_ERROR_CODE;

/**
 * <pre>
 * 1. ClassName :   HomehubRegister
 * 2. FileName  :   HomehubRegister.java
 * 3. Package   :   com.ntels.onecable.admin.view.things
 * 4. Date      :   2016-11-24
 * 5. Author    :   aaron
 * 6. Comment   :   Initialize
 * </pre>
 */
public class HomehubRegister extends CustomActivity implements View.OnClickListener,
        CustomDialog.OnMsgAlterToResult {

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

    private static final int DEFAULT_ANIMATION_DURATION = 800;
    private static final int DEFAULT_ANIMATION_TIMEOUT = 15000;
    private static final int CONNECT_MAX_TIME_SEC = 60;
    private static final long SCAN_PERIOD = CONNECT_MAX_TIME_SEC * 1000;

    private static final int MSG_COM_WS_DEVICE_REGISTER = 1;
    private static final int MSG_COM_P_DEVICEINFO = 2;

    int mType;

    Handler mComHandler = new Handler(new IncomingHandlerCallBack());
    private Handler mHandler = new Handler();
    private ScheduledFuture mScheduledFuture;
    private Boolean mIsPollingPause = false;
    private Boolean mIsPollingCancel = false;
    private Activity mActivity;
    private AppConfig mAppConfig;
    private Util mUtil = new Util();
    private CustomDialog mCustomDialog = new CustomDialog();
    private MdnsDiscovery mMdnsDiscovery;
    private MdnsDiscovery.onDiscoveryListener mOnDiscoveryListener;
    private HomehubRegisterAdapter mHomehubRegisterAdapter;
    private boolean mIsLoading = false;
    private boolean mIsDestroy = false;
    private int mMaxTime = CONNECT_MAX_TIME_SEC;
    private int mTotal = 0;
    private SwipeRefreshLayout mSwipeRefreshLayout;
    Runnable runnable = new Runnable() {
        public void run() {

            Dlog.v("Things mIsPollingCancel", mIsPollingCancel);
            Dlog.v("Things mIsPollingPause", mIsPollingPause);
            if (mIsPollingCancel) {
                mUtil.getView(mActivity, R.id.rlProgressLoading).setVisibility(View.INVISIBLE);
                mIsLoading = false;
                mScheduledFuture.cancel(false);
            }
            if (!mIsPollingPause) {
                mTotal++;
                mUtil.getTextView(mActivity, R.id.tvConnectTime).post(new Runnable() {
                    @Override
                    public void run() {

                        mUtil.getTextView(mActivity, R.id.tvConnectTime).setText((mMaxTime - mTotal) + "");
                    }
                });
                if (mTotal >= mMaxTime) {
                    Dlog.v("jino113 mIsLoading" + mIsLoading);
                    if (mIsLoading) {
                        mUtil.getTextView(mActivity, R.id.tvConnectTime).post(new Runnable() {
                            @Override
                            public void run() {

                                if (!mIsDestroy) {
                                    mIsLoading = false;
                                    mMdnsDiscovery.stop();

                                    mSwipeRefreshLayout.setEnabled(true);
                                    mUtil.getView(mActivity, R.id.rlProgressLoading).setVisibility(View.INVISIBLE);
                                    mUtil.getView(mActivity, R.id.btnResearch).setVisibility(View.VISIBLE);
                                    mUtil.getView(mActivity, R.id.btnResearch).setEnabled(true);
                                    mUtil.getTextView(mActivity, R.id.tvLoadingMsg).setText(R.string.layout_install_homehub_register_04);
                                    mUtil.getTextView(mActivity, R.id.tvLoadingMsg1).setText(R.string.layout_install_homehub_register_05);
                                }
                                mUtil.getTextView(mActivity, R.id.tvConnectTime).setText("");
                                if (mScheduledFuture != null) {
                                    mIsPollingPause = true;
                                    mScheduledFuture.cancel(false);
                                }
                                //실패 화면 호출
                                if (mHomehubRegisterAdapter.getItemCount() == 0) {
//                                mUtil.getView(mActivity, R.id.llPageRoot).setVisibility(View.INVISIBLE);
//                                    mIntent = new Intent(mActivity, HomehubBleStep2Err.class);
//                                    mUtil.callActivityForResultNoAnim(mActivity, mIntent, Constants.ACT_HOMEHUB_BLE_STEP2_ERR);
//                                } else if (mHomehubRegisterAdapter.getItemCount() == 1) {
//                                    mUtil.getView(mActivity, R.id.llBtn1).setVisibility(View.VISIBLE);
                                }
                            }
                        });

                        mScheduledFuture.cancel(false);
                    }
                }
            }
        }
    };
    private Intent mIntent;
    private Animation mLoadingAnimation;
    private String mHostAddress = "";
    private String mSerialNumber = "";

    public void recevicedWebSocket(Intent intentReceived) {

        int receivedState = intentReceived.getIntExtra(Constants.EXTRA_RESULT_STATE, WebSocketService.WEBSOCKET_RECEIVED_SUCESS);
        if (receivedState == WebSocketService.WEBSOCKET_RECEIVED_SUCESS) {
            try {
                String result = intentReceived.getStringExtra(Constants.EXTRA_RESULT);
                Dlog.v(result);
                JSONObject jsonObject = new JSONObject(result);
                String msgType = jsonObject.getString(Constants.KEY_MESSAGE_TYPE);
                LogUtil.i(TAG, "websocket message mType : " + msgType);
                if (msgType.equals(Constants.WEBSOCKET_TYPE_DEVICE_REGISTER)) {
                    resultWsDeviceRegister(jsonObject);
//                } else if (msgType.equals(Constants.WEBSOCKET_TYPE_AUTH)) {
//                    comHandler.sendMessageDelayed(comHandler.obtainMessage(MSG_COM_WS_DEVICE_REGISTER), Constants.HANDLER_DELAY_MILLIS);
                }
            } catch (JSONException ex) {
                ex.printStackTrace();
            }
        } else if (receivedState == WebSocketService.WEBSOCKET_RECEIVED_ERROR) {

            int errorCode = intentReceived.getIntExtra(EXTRA_ERROR_CODE, WebSocketService.WEBSOCKET_CONNECT_TIMEOUT);
            switch (errorCode) {

            }
        }
    }


    private void setIsPollingStop() {
        mUtil.getView(mActivity, R.id.rlProgressLoading).setVisibility(View.INVISIBLE);
        if (mScheduledFuture != null) {
            mIsLoading = false;
            mIsPollingPause = true;
            mScheduledFuture.cancel(false);
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


        mActivity = HomehubRegister.this;
        mAppConfig = (AppConfig) mActivity.getApplicationContext();
        mCustomDialog.setOnMsgAlterToResultEvent(this);

        setIsWebSocket(true);
        View viewToLoad = LayoutInflater.from(mActivity).inflate(R.layout.install_homehub_register, null);
        this.setContentView(viewToLoad);

        setToolbar();
        viewInit();
        startLoading();
    }

    /**
     * 툴바 셋팅.
     */
    private void setToolbar() {
        Toolbar toolbar = (Toolbar) mActivity.findViewById(R.id.toolbar);
        mUtil.setKeyboardHide(mActivity, toolbar);
        mUtil.getTextView(toolbar, R.id.tvToolbarTitle1).setVisibility(View.VISIBLE);
        mUtil.getTextView(toolbar, R.id.tvToolbarTitle2).setVisibility(View.GONE);
        mUtil.getTextView(toolbar, R.id.tvToolbarTitleDivider).setVisibility(View.GONE);
        mUtil.getTextView(toolbar, R.id.tvToolbarTitle3).setVisibility(View.GONE);
        mUtil.getTextView(toolbar, R.id.tvToolbarTitle4).setVisibility(View.GONE);
        mUtil.getTextView(toolbar, R.id.btnToolbarClose).setVisibility(View.GONE);
        mUtil.getTextView(toolbar, R.id.btnToolbarMore).setVisibility(View.GONE);

        mUtil.getTextView(toolbar, R.id.tvToolbarTitle1).setText(mUtil.getString(mActivity, R.string.layout_install_homehub_register_01));
    }

    /**
     * view initialize.
     */
    private void viewInit() {
        mUtil.getView(mActivity, R.id.btnResearch).setOnClickListener(this);
        mUtil.getView(mActivity, R.id.llBtn1).setOnClickListener(this);
        mUtil.getView(mActivity, R.id.llBtn2).setOnClickListener(this);
        mUtil.getView(mActivity, R.id.llBtn1).setEnabled(false);
        mUtil.getView(mActivity, R.id.llBtn1).setVisibility(View.GONE);
        mUtil.getView(mActivity, R.id.vLine).setVisibility(View.GONE);

        ArrayList<HashMap<String, Object>> alHomehubList = new ArrayList<>();
        mHomehubRegisterAdapter = new HomehubRegisterAdapter(alHomehubList);
        LinearLayoutManager llManager = new LinearLayoutManager(mActivity);
        RecyclerView rvHomehubList = (RecyclerView) findViewById(R.id.rvHomhubList);
        rvHomehubList.setLayoutManager(llManager);
        rvHomehubList.setAdapter(mHomehubRegisterAdapter);

        mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swiperefreshlayou);
        mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mSwipeRefreshLayout.setRefreshing(false);
                if (!mIsLoading) {
                    startLoading();
                }
            }
        });
    }

    /**
     * 로딩 이미지 애니메이션 시작.
     */
    private void startLoading() {
        mHomehubRegisterAdapter.clearItem();

        setPolling();
        mIsLoading = true;

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        mIntent = new Intent();
        if (resultCode == mActivity.RESULT_OK) {
            switch (requestCode) {
                case Constants.ACT_INSTALL_HOMEHUB_REGISTER_ERR:
                    startLoading();
                    break;
                case ACT_INSTALL_HOMEHUB_REGISTER_SUCESS:
                    mActivity.setResult(RESULT_OK, data);
                    finish();
                    break;
                default:
                    break;
            }
        } else {
            switch (requestCode) {
                case Constants.ACT_INSTALL_HOMEHUB_REGISTER_ERR:
                    Boolean isFlowEnd = data.getBooleanExtra(Constants.EXTRA_FLOW_END_FLAG, false);
                    Boolean isEnd = data.getBooleanExtra(Constants.EXTRA_END_FLAG, false);
                    if (isFlowEnd) {
                        mUtil.getView(mActivity, R.id.llPageRoot).setVisibility(View.VISIBLE);
                    } else if (isEnd) {
                        mActivity.setResult(RESULT_CANCELED, data);
                        finish();
                    }
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    public void onBackPressed() {

        mCustomDialog.msgAlert(mActivity, Constants.MSG905);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (mIsLoading) {
            mIsDestroy = true;
            if (mScheduledFuture != null) {
                mIsPollingPause = true;
                mScheduledFuture.cancel(false);
            }
        }
    }

    @Override
    public void resultCustomDialogResponse(int msgId, int btnResult) {
        switch (msgId) {
            case Constants.MSG807:
                if (btnResult == 1) {
                    mComHandler.sendMessageDelayed(mComHandler.obtainMessage(mType), Constants.HANDLER_DELAY_MILLIS);
                }
                break;
            case Constants.MSG905:
                if (btnResult == 1) {
                    setResult(RESULT_CANCELED);
                    finish();
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.llBtn1:
                setIsPollingStop();
                dialog_show();
                mComHandler.sendMessageDelayed(mComHandler.obtainMessage(MSG_COM_WS_DEVICE_REGISTER), Constants.HANDLER_DELAY_MILLIS);
                break;
            case R.id.llBtn2:
                onBackPressed();
                break;
            case R.id.btnResearch:
                mUtil.getView(mActivity, R.id.btnResearch).setEnabled(false);
                startLoading();
                break;
            default:
                break;
        }
    }

    /**
     * 서비스허브에 홈허브 디바이스를 등록 요청한다.
     */
    private void sendWsDeviceRegister() {
        int position = mHomehubRegisterAdapter.checkItem();
        HashMap<String, Object> hmItem = mHomehubRegisterAdapter.getItem(position);
        mSerialNumber = mUtil.null2string(hmItem.get(Constants.MDNS_KEY_INFO_SERIAL_NUMBER));
        String modelNumber = mUtil.null2string(hmItem.get(Constants.MDNS_KEY_INFO_MDOEL_NUMBER));
        String manufacturer = mUtil.null2string(hmItem.get(Constants.MDNS_KEY_INFO_MANUFACTURER));
        String profileVersion = mUtil.null2string(hmItem.get(Constants.MDNS_KEY_INFO_PROFILE_VERSION));
        mHostAddress = mUtil.null2string(hmItem.get(Constants.MDNS_KEY_INFO_HOST_ADDRESS));

        HashMap<String, Object> sendParams = new HashMap<>();
        sendParams.put(Constants.KEY_MESSAGE_TYPE, Constants.WEBSOCKET_TYPE_DEVICE_REGISTER);
        sendParams.put(Constants.KEY_CUST_ID, mAppConfig.getCustId());
        sendParams.put(Constants.KEY_CTRT_GRP_ID, mAppConfig.getCtrtGroupId());
        sendParams.put(Constants.KEY_CTRT_ID, mAppConfig.getCustomerCtrtId());
        sendParams.put(Constants.KEY_DEVICE_MANUFACTURER, manufacturer);
        sendParams.put(Constants.KEY_DEVICE_MODEL_NUMBER, modelNumber);
        sendParams.put(Constants.KEY_DEVICE_SERIAL_NUMBER, mSerialNumber);
        sendParams.put(Constants.KEY_DEVICE_PROFILE_VERSION, profileVersion);
//        sendParams.put(Constants.KEY_DEVICE_PASSWORD, mPass);
        sendParams.put(Constants.KEY_REQUEST_ID, mAppConfig.getSelectServicehubRequestId());

        Dlog.v(sendParams.toString());
        getWebSocketService().send(Constants.WEBSOCKET_SEND_DEVICE_REGISTER, sendParams);
    }

    /**
     * 서비스허브에 홈허브 디바이스 등록 요청 결과.
     *
     * @param joResult 결과 data
     *
     * @exception JSONException json parsing exception
     */
    private void resultWsDeviceRegister(JSONObject joResult) throws JSONException {
        dialog_dismiss();
        String resultCode = mUtil.null2string(joResult.get(Constants.KEY_RESULT_CODE));
        String resultMsg = "";
        if (joResult.has(Constants.KEY_RESULT_MSG)) {
            resultMsg = mUtil.null2string(joResult.get(Constants.KEY_RESULT_MSG));
        }
        if ("00".equals(resultCode)) {
            mAppConfig.setSelectHomehubDeviceId(mUtil.null2string(joResult.get(Constants.KEY_DEVICE_ID)));
            mAppConfig.setSelectHomehubDeviceKey(mUtil.null2string(joResult.get(Constants.KEY_DEVICE_KEY)));

            mComHandler.sendMessageDelayed(mComHandler.obtainMessage(MSG_COM_P_DEVICEINFO), Constants.HANDLER_DELAY_MILLIS);
        } else {
            final String finalResultMsg = resultMsg;
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Intent intent = new Intent(mActivity, HomehubRegisterErr.class);
                    intent.putExtra(Constants.EXTRA_DEVICE_SERIAL_NUMBER, mSerialNumber);
                    mUtil.callActivityForResultNoAnim(mActivity, intent, Constants.ACT_INSTALL_HOMEHUB_REGISTER_ERR);
//                    mUtil.setShowToast(mActivity, finalResultMsg, Toast.LENGTH_SHORT);
                }
            });
        }
    }

    /**
     * 등록하려는 홈허브에 device_id, device_key 정보를 전달한다.
     */
    private void sendPostDeviceInfo() {

        try {
            HttpSend httpSend = new HttpSend(mActivity, !mIsLoading);
            httpSend.setOnDataSendToReslutEvent(new OnDataSendToReslut() {
                @Override
                public void resultResponse(Response result) {

                    resultPostDeviceInfo(result);
                }
            });
            httpSend.P_deviceinfo(mHostAddress,
                    mAppConfig.getSelectHomehubDeviceId(),
                    mAppConfig.getSelectHomehubDeviceKey());
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 등록하려는 홈허브에 device_id, device_key 정보 전달 결과.
     *
     * @param response 결과 data
     */
    private void resultPostDeviceInfo(Response response) {
        try {
            if (response.getStatusCode() == Response.OK) {
                JSONObject joResult = new JSONObject(response.getContent());
                Dlog.v(joResult.toString());

                String result = mUtil.null2string(joResult.get(Constants.KEY_RESULT));
                if ("SUCCESS".equalsIgnoreCase(result)) {
                    Intent intent = new Intent(mActivity, HomehubRegisterSucess.class);
                    intent.putExtra(Constants.EXTRA_DEVICE_SERIAL_NUMBER, mSerialNumber);
                    mUtil.callActivityForResultNoAnim(mActivity, intent, Constants.ACT_INSTALL_HOMEHUB_REGISTER_SUCESS);
                }
            } else {
                JSONObject joResult = new JSONObject(response.getContent());
                Dlog.v(joResult.toString());
                // TODO : 에러 메세지 정의
                mUtil.setShowToast(mActivity, "홈허브를 재시작해주세요.", Toast.LENGTH_SHORT);
                Intent intent = new Intent(mActivity, HomehubRegisterSucess.class);
                intent.putExtra(Constants.EXTRA_DEVICE_SERIAL_NUMBER, mSerialNumber);
                mUtil.callActivityForResultNoAnim(mActivity, intent, Constants.ACT_INSTALL_HOMEHUB_REGISTER_SUCESS);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            mCustomDialog.msgAlert(mActivity, Constants.MSG807);
        }
    }

    /**
     * (등록 진행하기 전) 해당 디바이스의 기 등록여부를 조회 요청한다.
     *
     * @param item  검색된 디바이스 정보
     * @param index 검색된 디바이스 index
     */
    private void sendGetDeviceRegistState(HashMap<String, Object> item, final int index) {
        try {
            HttpSend httpSend;

            httpSend = new HttpSend(mActivity, !mIsLoading);
            //            httpSend = new HttpSend(mActivity);

            httpSend.setOnDataSendToReslutEvent(new OnDataSendToReslut() {
                @Override
                public void resultResponse(Response result) {

                    resultGetDeviceRegistState(result, index);
                }
            });

            String manufacturer = mUtil.null2string(item.get(Constants.KEY_MANUFACTURER));
            String modelId = mUtil.null2string(item.get(Constants.KEY_MODEL_NUMBER));
            String serialNumber = mUtil.null2string(item.get(Constants.KEY_SERIAL_NUMBER));

            httpSend.getDeviceRegistState(manufacturer, modelId, serialNumber);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * (등록 진행하기 전) 해당 디바이스의 기 등록여부 조회 요청 결과.
     *
     * @param result 결과 data
     * @param index  조회한 디바이스 index
     */
    private void resultGetDeviceRegistState(Response result, int index) {

        try {
            if (result.getStatusCode() == Response.OK) {
                JSONObject joResult = new JSONObject(result.getContent());
                String resultCode = mUtil.null2string(joResult.get(Constants.KEY_RESULT_CODE));
                String deviceId = "";
                if (joResult.has(Constants.KEY_DEVICE_ID)) {
                    deviceId = mUtil.null2string(joResult.get(Constants.KEY_DEVICE_ID));
                }

                LogUtil.i(TAG, "index : " + index);

                /** NE : 등록되지 않은 홈허브, E1 : 다른 사용자에게 등록되어 있는 홈허브 */
                if ("NE".equalsIgnoreCase(resultCode) || "E1".equalsIgnoreCase(resultCode)) {
                    HashMap<String, Object> item = mHomehubRegisterAdapter.getItem(index);
                    item.put(Constants.MDNS_KEY_INFO_HOMEHUB_STATUS, resultCode);
                    item.put(Constants.KEY_DEVICE_ID, deviceId);
                    if (mUtil.getView(mActivity, R.id.rvHomhubList).getVisibility() == View.GONE) {
                        mUtil.getView(mActivity, R.id.rvHomhubList).setVisibility(View.VISIBLE);
                        mUtil.getView(mActivity, R.id.llBtn1).setVisibility(View.VISIBLE);
                        mUtil.getView(mActivity, R.id.vLine).setVisibility(View.VISIBLE);
//                        mUtil.getView(mActivity, R.id.width_section).setVisibility(View.VISIBLE);
                    }
                    mHomehubRegisterAdapter.notifyDataSetChanged();
                }
            } else {
                JSONObject joResult = new JSONObject(result.getContent());
                Dlog.v(joResult.toString());
//                String errorCode = mUtil.null2string(joResult.get(Constants.KEY_ERR_CODE));
                String resultCode = mUtil.null2string(joResult.get(Constants.KEY_RESULT_CODE));
//                String errorMsg = mUtil.null2string(joResult.get(Constants.KEY_ERR_MSG));
                String resultMsg = mUtil.null2string(joResult.get(Constants.KEY_RESULT_MSG));

                if ("401".equals(resultCode)) {
                    mCustomDialog.msgAlert(mActivity, Constants.MSG998, resultMsg);
                } else if ("401-106".equals(resultCode)) {
                    mCustomDialog.msgAlert(mActivity, Constants.MSG997, resultMsg);
                } else {
                    mCustomDialog.msgAlert(mActivity, Constants.MSG807);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            mCustomDialog.msgAlert(mActivity, Constants.MSG807);
        }
    }

    /**
     * 노드 추가 60초 타이머 스케줄러.
     */
    private void setPolling() {

        mSwipeRefreshLayout.setRefreshing(false);
        mTotal = 0;
        Dlog.v("Things setPolling");
        ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();

        mIsPollingPause = false;
        mIsPollingCancel = false;
        mScheduledFuture = scheduler.scheduleAtFixedRate(runnable, 1, 1, TimeUnit.SECONDS);

        mSwipeRefreshLayout.setEnabled(false);
        mUtil.getView(mActivity, R.id.rlProgressLoading).setVisibility(View.VISIBLE);
        mUtil.getView(mActivity, R.id.btnResearch).setVisibility(View.GONE);
        mUtil.getTextView(mActivity, R.id.tvLoadingMsg).setText(R.string.layout_install_homehub_register_02);
        mUtil.getTextView(mActivity, R.id.tvLoadingMsg1).setText(R.string.layout_install_homehub_register_03);

        mOnDiscoveryListener = new MdnsDiscovery.onDiscoveryListener() {
            @Override
            public void onFindDevice(HashMap<String, Object> homehubInfo) {
                mHomehubRegisterAdapter.addItem(homehubInfo);
            }
        };
        mMdnsDiscovery = new MdnsDiscovery(mOnDiscoveryListener);
        mMdnsDiscovery.start();
    }


    /**
     * 서버 요청 핸들러.
     */
    class IncomingHandlerCallBack implements Handler.Callback {

        @Override
        public boolean handleMessage(Message msg) {

            mType = msg.what;
            switch (msg.what) {
                case MSG_COM_WS_DEVICE_REGISTER:
                    sendWsDeviceRegister();
                    break;
                case MSG_COM_P_DEVICEINFO:
                    sendPostDeviceInfo();
                    break;
                default:
                    break;
            }
            return true;
        }
    }

    /**
     * Homehub register adapter.
     *
     * @author aaron
     */
    public class HomehubRegisterAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

        private ArrayList<HashMap<String, Object>> mHomehubList;
        private int mCheckPosition;

        HomehubRegisterAdapter(ArrayList<HashMap<String, Object>> homehubList) {
            this.mHomehubList = homehubList;
        }

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

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
            HashMap<String, Object> hmItem = new HashMap<String, Object>();
            hmItem = mHomehubList.get(position);
            Device deviceView = (Device) holder;

            String serialNumber = mUtil.null2string(hmItem.get(Constants.MDNS_KEY_INFO_SERIAL_NUMBER));
            String modelNumber = mUtil.null2string(hmItem.get(Constants.MDNS_KEY_INFO_MDOEL_NUMBER));
            String manufacturer = mUtil.null2string(hmItem.get(Constants.MDNS_KEY_INFO_MANUFACTURER));
            String profileVersion = mUtil.null2string(hmItem.get(Constants.MDNS_KEY_INFO_PROFILE_VERSION));
            String status = mUtil.null2string(hmItem.get(Constants.MDNS_KEY_INFO_HOMEHUB_STATUS));
            String deviceId = mUtil.null2string(hmItem.get(Constants.KEY_DEVICE_ID));
            String hostAddress = mUtil.null2string(hmItem.get(Constants.MDNS_KEY_INFO_HOST_ADDRESS));
            String checkYn = mUtil.null2string(hmItem.get(Constants.KEY_CHECK_YN));

            LogUtil.i(TAG, "status : " + status);

            // 기 등록조회를 하지 않은 항목은 리스트에 노출시키지 않는다.
            if (status.isEmpty()) {
                return;
            }

            deviceView.tvSerialNumber.setText(getString(R.string.layout_things_guide_31, serialNumber));
            deviceView.tvModelName.setText(getString(R.string.layout_things_guide_32, modelNumber, manufacturer));
            if (checkYn.equals("Y")) {
                deviceView.llRoot.setSelected(true);
            } else {
                deviceView.llRoot.setSelected(false);
            }
            deviceView.llRoot.setTag(position);
            deviceView.llRoot.setOnClickListener(null);
            if ("NE".equalsIgnoreCase(status)) {
                deviceView.tvHomehubStatus.setText(R.string.layout_things_guide_33);
                deviceView.tvHomehubStatus.setEnabled(true);
                deviceView.ivRadio.setEnabled(true);
                deviceView.llRoot.setOnClickListener(new View.OnClickListener() {
                    int tag = 0;

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

                        for (HashMap<String, Object> hm : mHomehubList) {
                            hm.put(Constants.KEY_CHECK_YN, "N");
                        }
                        mHomehubList.get(position).put(Constants.KEY_CHECK_YN, "Y");
                        mCheckPosition = position;
                        mUtil.getView(mActivity, R.id.llBtn1).setEnabled(true);
                        notifyDataSetChanged();
                    }
                });
            } else if ("E1".equalsIgnoreCase(status)) {
                deviceView.tvHomehubStatus.setText(R.string.layout_things_guide_34);
                deviceView.tvHomehubStatus.setEnabled(false);
                deviceView.ivRadio.setEnabled(false);
            } else {
                deviceView.tvHomehubStatus.setVisibility(View.GONE);
                deviceView.ivRadio.setVisibility(View.GONE);
            }
        }

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

        /**
         * 검색된 디바이스를 adapter에 추가.
         *
         * @param item 검색된 디바이스 정보
         */
        public void addItem(HashMap<String, Object> item) {
            LogUtil.i(TAG, "addItem : " + item.toString());
            // MDNS 검색 시 게이트웨이 service info 정보가 안오는 경우가 있음.
            if (null == item || !item.containsKey(Constants.MDNS_KEY_INFO_SERIAL_NUMBER)) {
                Dlog.v("jino test1");
                return;
            }
            for (HashMap<String, Object> hm : mHomehubList) {
                if (hm.get(Constants.MDNS_KEY_INFO_SERIAL_NUMBER).equals(item.get(Constants.MDNS_KEY_INFO_SERIAL_NUMBER))) {
                    Dlog.v("jino test2");
                    return;
                }
            }
            Dlog.v("jino test3");
            item.put(Constants.KEY_CHECK_YN, "N");
            int iposition = getItemCount();
            mHomehubList.add(item);
            Dlog.v("jino test4");
//            sendGetDeviceRegistState(item, getItemCount() - 1);
            sendGetDeviceRegistState(item, iposition);
        }

        /**
         * 홈허브 리스트 초기화.
         */
        public void clearItem() {
            this.mHomehubList.clear();
            mUtil.getView(mActivity, R.id.rvHomhubList).setVisibility(View.GONE);
            mUtil.getView(mActivity, R.id.llBtn1).setVisibility(View.GONE);
            mUtil.getView(mActivity, R.id.vLine).setVisibility(View.GONE);
        }

        /**
         * 홈허브 리스트 초기화.
         */
        public int checkItem() {
            return mCheckPosition;
        }

        /**
         * position에 해당하는 디바이스 정보를 반환한다.
         *
         * @param position 리스트 내 디바이스 index
         *
         * @return position에 해당하는 디바이스 정보
         */
        public HashMap<String, Object> getItem(int position) {
            return mHomehubList.get(position);
        }
    }

    /**
     * Item view holder.
     *
     * @author aaron
     */
    public class Device extends RecyclerView.ViewHolder {

        public LinearLayout llRoot;
        public TextView tvSerialNumber;
        public TextView tvModelName;
        public TextView tvHomehubStatus;
        public ImageView ivRadio;

        /**
         * Device view holder 생성자.
         *
         * @param itemView Recycler에 보여줄 view
         */
        public Device(View itemView) {
            super(itemView);
            llRoot = (LinearLayout) itemView.findViewById(R.id.llRoot);
            tvSerialNumber = (TextView) itemView.findViewById(R.id.tvSerialNumber);
            tvModelName = (TextView) itemView.findViewById(R.id.tvModelName);
            tvHomehubStatus = (TextView) itemView.findViewById(R.id.tvHomehubStatus);
            ivRadio = (ImageView) itemView.findViewById(R.id.ivRadio);
        }
    }

}
