package com.ntels.onecable.view.things;

import com.ntels.onecable.R;
import com.ntels.onecable.common.Constants;
import com.ntels.onecable.common.c_interface.OnDataSendToReslut;
import com.ntels.onecable.common.http.HttpSend;
import com.ntels.onecable.common.http.Response;
import com.ntels.onecable.common.mdns.MdnsDiscovery;
import com.ntels.onecable.common.util.Dlog;
import com.ntels.onecable.common.util.LogUtil;
import com.ntels.onecable.common.util.Util;
import com.ntels.onecable.common.widget.CustomActivity;
import com.ntels.onecable.view.dialog.CustomDialog;

import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
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.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

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

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

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

    private static final int DEFAULT_ANIMATION_DURATION = 800;
    private static final int DEFAULT_ANIMATION_TIMEOUT = 15000;

    int mType;

    private Activity mActivity;
    private Util mUtil = new Util();
    private CustomDialog mCustomDialog = new CustomDialog();
    private MdnsDiscovery mMdnsDiscovery;
    private MdnsDiscovery.onDiscoveryListener mOnDiscoveryListener;
    private ThingsHomehubRegisterAdapter mHomehubRegisterAdapter;
    private boolean mIsLoading = false;
    private boolean mIsDestroy = false;
    private SwipeRefreshLayout mSwipeRefreshLayout;
    private Intent mIntent;
    private Animation mLoadingAnimation;

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


        mActivity = ThingsHomehubRegister.this;
        mCustomDialog.setOnMsgAlterToResultEvent(this);

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

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

    @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_THINGS_HOMEHUB_SET_PASSWORD:
                case Constants.ACT_THINGS_HOMEHUB_ASSIGN_PASSWORD:
                    mIntent = new Intent();
                    setResult(RESULT_OK, mIntent);
                    finish();
                    break;
                default:
                    break;
            }
        } else {
            switch (requestCode) {
                case Constants.ACT_THINGS_HOMEHUB_SET_PASSWORD:
                case Constants.ACT_THINGS_HOMEHUB_ASSIGN_PASSWORD:
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    public void onBackPressed() {

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

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

        if (mIsLoading) {
            mIsDestroy = true;
            mLoadingAnimation.cancel();
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.llBtn1:
                mCustomDialog.msgAlert(mActivity, Constants.MSG905);
                break;
            default:
                break;
        }
    }

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

    /**
     * (등록 진행하기 전) 해당 디바이스의 기 등록여부를 조회 요청한다.
     *
     * @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.G_devices_mf_id_model_id_sn(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.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 errorMsg = mUtil.null2string(joResult.get(Constants.KEY_ERR_MSG));

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

    /**
     * view initialize.
     */
    private void viewInit() {
        mUtil.getView(mActivity, R.id.llBtn1).setOnClickListener(this);

        ArrayList<HashMap<String, Object>> alHomehubList = new ArrayList<>();
        mHomehubRegisterAdapter = new ThingsHomehubRegisterAdapter(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) {
                    mHomehubRegisterAdapter.clearItem();
                    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.btnToolbarDel).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_things_guide_01));
    }

    /**
     * 로딩 이미지 애니메이션 시작.
     */
    private void startLoading() {
        mIsLoading = true;
        mLoadingAnimation = AnimationUtils.loadAnimation(mActivity, R.anim.progress_anim);
        mLoadingAnimation.setDuration(DEFAULT_ANIMATION_DURATION);
        mLoadingAnimation.setAnimationListener(new Animation.AnimationListener() {

            @Override
            public void onAnimationStart(Animation animation) {
                LogUtil.i(TAG, "onAnimationStart");
                mOnDiscoveryListener = new MdnsDiscovery.onDiscoveryListener() {
                    @Override
                    public void onFindDevice(HashMap<String, Object> homehubInfo) {
                        mHomehubRegisterAdapter.addItem(homehubInfo);
                    }
                };
                mMdnsDiscovery = new MdnsDiscovery(mOnDiscoveryListener);
                mMdnsDiscovery.start();
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mLoadingAnimation.cancel();
                    }
                }, DEFAULT_ANIMATION_TIMEOUT);
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                LogUtil.i(TAG, "onAnimationEnd");
                mIsLoading = false;
                if (!mIsDestroy) {
                    mUtil.getImageView(mActivity, R.id.ivLoadingProgress)
                            .setImageResource(R.drawable.img_complet_small_s01);
                    mUtil.getTextView(mActivity, R.id.tvLoadingMsg)
                            .setText(R.string.layout_things_guide_35);
                }
                mMdnsDiscovery.stop();
            }

            @Override
            public void onAnimationRepeat(Animation animation) {
                LogUtil.i(TAG, "onAnimationRepeat");
            }
        });
        mUtil.getImageView(mActivity, R.id.ivLoadingProgress)
                .setImageResource(R.drawable.img_progress_small_black_s01);
        mUtil.getTextView(mActivity, R.id.tvLoadingMsg)
                .setText(R.string.layout_things_guide_30);
        mUtil.getImageView(mActivity, R.id.ivLoadingProgress)
                .startAnimation(mLoadingAnimation);
    }

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

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

        ThingsHomehubRegisterAdapter(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, int position) {
            HashMap<String, Object> hmItem = new HashMap<String, Object>();
            hmItem = mHomehubList.get(position);
            Device deviceView = (Device) holder;

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

            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 ("NE".equalsIgnoreCase(status)) {
                deviceView.ivHomehubIcon.setImageResource(R.drawable.img_homehub_icon_hub_enroll);
                deviceView.tvHomehubStatus.setText(R.string.layout_things_guide_33);
            } else if ("E1".equalsIgnoreCase(status)) {
                deviceView.ivHomehubIcon.setImageResource(R.drawable.img_homehub_icon_hub_done);
                deviceView.tvHomehubStatus.setText(R.string.layout_things_guide_34);
            } else {
                deviceView.ivHomehubIcon.setVisibility(View.GONE);
                deviceView.tvHomehubStatus.setVisibility(View.GONE);
            }

            deviceView.llRoot.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (mIsLoading) {
                        mLoadingAnimation.cancel();
                    }
                    if ("NE".equalsIgnoreCase(status)) {
                        Intent intent = new Intent(mActivity, ThingsHomehubSetPassword.class);
                        intent.putExtra(Constants.EXTRA_DEVICE_MANUFACTURER, manufacturer);
                        intent.putExtra(Constants.EXTRA_DEVICE_MODEL_NUMBER, modelNumber);
                        intent.putExtra(Constants.EXTRA_DEVICE_SERIAL_NUMBER, serialNumber);
                        intent.putExtra(Constants.EXTRA_DEVICE_PROFILE_VERSION, profileVersion);
                        intent.putExtra(Constants.EXTRA_MDNS_HOST_ADDRESS, hostAddress);
                        mUtil.callActivityForResultNoAnim(mActivity, intent,
                                Constants.ACT_THINGS_HOMEHUB_SET_PASSWORD);
                    } else if ("E1".equalsIgnoreCase(status)) {
                        Intent intent = new Intent(mActivity, ThingsHomehubAssignPassword.class);
                        intent.putExtra(Constants.EXTRA_DEVICE_ID, deviceId);
                        mUtil.callActivityForResultNoAnim(mActivity, intent,
                                Constants.ACT_THINGS_HOMEHUB_ASSIGN_PASSWORD);
                    }
                }
            });
        }

        @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)) {
                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))) {
                    return;
                }
            }
            mHomehubList.add(item);
            sendGetDeviceRegistState(item, getItemCount() - 1);
        }

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

        /**
         * 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 ImageView ivHomehubIcon;
        public TextView tvHomehubStatus;

        /**
         * 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);
            ivHomehubIcon = (ImageView) itemView.findViewById(R.id.ivHomehubIcon);
            tvHomehubStatus = (TextView) itemView.findViewById(R.id.tvHomehubStatus);
        }
    }

}
