package com.ntels.kneet.v3.view.things;

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

import com.ntels.kneet.v3.R;
import com.ntels.kneet.v3.common.AppConfig;
import com.ntels.kneet.v3.common.Constants;
import com.ntels.kneet.v3.common.c_interface.OnDataSendToReslut;
import com.ntels.kneet.v3.common.http.HttpSend;
import com.ntels.kneet.v3.common.http.Response;
import com.ntels.kneet.v3.common.mdns.MdnsDiscovery;
import com.ntels.kneet.v3.common.util.Dlog;
import com.ntels.kneet.v3.common.util.LogUtil;
import com.ntels.kneet.v3.common.util.Util;
import com.ntels.kneet.v3.common.websocket.WebSocketService;
import com.ntels.kneet.v3.common.websocket.onWebSocketResponse;
import com.ntels.kneet.v3.common.widget.CustomActivity;
import com.ntels.kneet.v3.view.dialog.CustomDialog;

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

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

/**
 * 1. ClassName :   Things_Homehub_Register
 * 2. FileName  :   Things_Homehub_Register.java
 * 3. Package   :   com.ntels.kneet.v3.view.things
 * 4. Date      :   2016-07-18
 * 5. Author    :   aaron
 * 6. Comment   :   Initialize
 */
public class Things_Homehub_Register extends CustomActivity implements View.OnClickListener,
                                                                       CustomDialog.OnMsgAlterToResult {

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

    private              int                                iType = 0;
    private static final int                                MSG_COM_G_DEVICES_HOMEHUB_REGISTRATION_STATUS = 1;

    private Activity                                        act;
    private Util                                            util = new Util();
    private AppConfig                                       appConfig;
    private CustomDialog                                    customDialog = new CustomDialog();
    private MdnsDiscovery                                   mdnsDiscovery;
    private MdnsDiscovery.onDiscoveryListener               onDiscoveryListener;
    private Things_Homehub_Register_Adapter                 homehubRegisterAdapter;
    private boolean                                         isLoading = false;
    private boolean                                         isDestroy = false;
    private SwipeRefreshLayout                              swipeRefreshLayout;
    private HashMap<String, Object>                         findedHomhub;
    private Intent                                          intent;
    private Animation                                       loadingAnimation;

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


        act = Things_Homehub_Register.this;
        appConfig = new AppConfig();
        customDialog.setOnMsgAlterToResultEvent(this);

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

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

    private void viewInit() {
        util.getView(act, R.id.llBtn1).setOnClickListener(this);

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

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

    private void setToolbar() {
        Toolbar toolbar = (Toolbar) act.findViewById(R.id.toolbar);
        util.setKeyboardHide(act, toolbar);
        util.getTextView(toolbar, R.id.tvToolbarTitle1).setVisibility(View.VISIBLE);
        util.getTextView(toolbar, R.id.tvToolbarTitle2).setVisibility(View.GONE);
        util.getTextView(toolbar, R.id.tvToolbarTitleDivider).setVisibility(View.GONE);
        util.getTextView(toolbar, R.id.tvToolbarTitle3).setVisibility(View.GONE);
        util.getTextView(toolbar, R.id.tvToolbarTitle4).setVisibility(View.GONE);
        util.getTextView(toolbar, R.id.btnToolbarDel).setVisibility(View.GONE);
        util.getTextView(toolbar, R.id.btnToolbarClose).setVisibility(View.GONE);
        util.getTextView(toolbar, R.id.btnToolbarMore).setVisibility(View.GONE);

        util.getTextView(toolbar, R.id.tvToolbarTitle1).setText(util.getString(act, R.string.layout_things_guide_01));
    }

    private void startLoading() {
        isLoading = true;
        loadingAnimation = AnimationUtils.loadAnimation(act, R.anim.progress_anim);
        loadingAnimation.setDuration(800);
//        animation.setInterpolator(new Interpolator() {
//            private final int frameCount = 10;
//            @Override
//            public float getInterpolation(float input) {
//                return (float) Math.floor(input * frameCount) / frameCount;
//            }
//        });
        loadingAnimation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
                LogUtil.i(TAG, "onAnimationStart");
                onDiscoveryListener = new MdnsDiscovery.onDiscoveryListener() {
                    @Override
                    public void onFindDevice(HashMap<String, Object> homehubInfo) {
                        findedHomhub = homehubInfo;
                        ComHandler.sendMessageDelayed(ComHandler.obtainMessage(MSG_COM_G_DEVICES_HOMEHUB_REGISTRATION_STATUS), 10);
//                        homehubRegisterAdapter.addItem(homehubInfo);
                    }
                };
                mdnsDiscovery = new MdnsDiscovery(onDiscoveryListener);
                mdnsDiscovery.start();
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        loadingAnimation.cancel();
                    }
                }, 40000);
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                LogUtil.i(TAG, "onAnimationEnd");
                isLoading = false;
                if ( !isDestroy ) {
                    util.getImageView(act, R.id.ivLoadingProgress).setImageResource(R.drawable.img_complet_small_s01);
                    util.getTextView(act, R.id.tvLoadingMsg).setText(R.string.layout_things_guide_35);
                }
                mdnsDiscovery.stop();
            }

            @Override
            public void onAnimationRepeat(Animation animation) {
                LogUtil.i(TAG, "onAnimationRepeat");
                /*HashMap<String, Object> map = new HashMap<String, Object>();
                map.put("serialNumber", "1234-1234-1234-1234");
                map.put("modelName", "addg-101");
                map.put("mfName", "ntels");
                map.put("status", "Y");

                onDiscoveryListener.onFindDevice(map);*/
            }
        });
        util.getImageView(act, R.id.ivLoadingProgress).setImageResource(R.drawable.img_progress_small_black_s01);
        util.getTextView(act, R.id.tvLoadingMsg).setText(R.string.layout_things_guide_30);
        util.getImageView(act, R.id.ivLoadingProgress).startAnimation(loadingAnimation);
    }

    /**
     * Called when a view has been clicked.
     *
     * @param v The view that was clicked.
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.llBtn1:
                customDialog.MsgAlert(act, Constants.MSG905);
                break;
        }
    }

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

    /**
     * <PRE>
     * 1. MethodName: send_G_devices_mf_id_model_id_sn
     * 2. ClassName :
     * 3. Comment   : [Send][GET](등록 진행하기 전) 해당 디바이스의 기 등록여부를 조회한다.
     * 4. Developer : 정백호
     * 5. Created   : 2016. 07.
     * </PRE>
     */
    private void send_G_devices_mf_id_model_id_sn() {
        try {
            HttpSend httpSend;

            httpSend = new HttpSend(act, !isLoading);
            //            httpSend = new HttpSend(act);

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

                    result_G_devices_mf_id_model_id_sn(result);
                }
            });

            String manufacturer = util.null2string(findedHomhub.get(Constants.HTTP_manufacturer));
            String modelId = util.null2string(findedHomhub.get(Constants.HTTP_model_number));
            String serialNumber = util.null2string(findedHomhub.get(Constants.HTTP_serial_number));

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

    /**
     * <PRE>
     * 1. MethodName: result_G_devices_mf_id_model_id_sn
     * 2. ClassName :
     * 3. Comment   : [Result][GET](등록 진행하기 전) 해당 디바이스의 기 등록여부를 조회한다.
     * 4. Developer : 정백호
     * 5. Created   : 2016. 07.
     * </PRE>
     */
    private void result_G_devices_mf_id_model_id_sn(Response rpResult) {

        try {
            if ( rpResult.getStatusCode() == 200 ) {
                JSONObject joResult = new JSONObject(rpResult.getContent());
                String resultCode = util.null2string(joResult.get(Constants.HTTP_result_code));
                String deviceId = "";
                if ( joResult.has(Constants.HTTP_device_id) ) {
                    deviceId = util.null2string(joResult.get(Constants.HTTP_device_id));
                }

                /** NE : 등록되지 않은 홈허브, E1 : 다른 사용자에게 등록되어 있는 홈허브 */
                if ( resultCode.equalsIgnoreCase("NE") || resultCode.equalsIgnoreCase("E1")) {
                    findedHomhub.put(Constants.MDNS_KEY_INFO_HOMEHUB_STATUS, resultCode);
                    findedHomhub.put(Constants.HTTP_device_id, deviceId);
                    homehubRegisterAdapter.addItem(findedHomhub);
                }
            } else {
                JSONObject joResult = new JSONObject(rpResult.getContent());
                Dlog.v(joResult.toString());
                String sERR_CODE = util.null2string(joResult.get(Constants.HTTP_err_code));
                String sERR_MSG = util.null2string(joResult.get(Constants.HTTP_err_msg));

                if ( sERR_CODE.equals("401") ) {
                    customDialog.MsgAlert(act, Constants.MSG998, sERR_MSG);
                } else if ( sERR_CODE.equals("401-106") ) {
                    customDialog.MsgAlert(act, Constants.MSG997, sERR_MSG);
                } else {

                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            customDialog.MsgAlert(act, Constants.MSG807);
        }
    }

    Handler ComHandler = new Handler(new IncomingHandlerCallBack());

    class IncomingHandlerCallBack implements Handler.Callback {

        @Override public boolean handleMessage(Message msg) {

            iType = msg.what;
            switch (msg.what) {
                case MSG_COM_G_DEVICES_HOMEHUB_REGISTRATION_STATUS:
                    send_G_devices_mf_id_model_id_sn();
                    break;

                default:
                    break;
            }
            return true;
        }
    }

    public class Things_Homehub_Register_Adapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

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

        Things_Homehub_Register_Adapter(ArrayList<HashMap<String, Object>> alHomehubList) {
            this.alHomehubList = alHomehubList;
        }

        public void addItem(HashMap<String, Object> item) {
            alHomehubList.add(item);
            util.getView(act, R.id.rvHomhubList).setVisibility(View.VISIBLE);
            util.getView(act, R.id.width_section).setVisibility(View.VISIBLE);
            notifyDataSetChanged();
        }

        public void clearItem() {
            this.alHomehubList.clear();
            util.getView(act, R.id.rvHomhubList).setVisibility(View.GONE);
            util.getView(act, R.id.width_section).setVisibility(View.GONE);
        }

        /**
         * Called when RecyclerView needs a new {@link ViewHolder} of the given type to represent
         * an item.
         * <p/>
         * This new ViewHolder should be constructed with a new View that can represent the items
         * of the given type. You can either create a new View manually or inflate it from an XML
         * layout file.
         * <p/>
         * The new ViewHolder will be used to display items of the adapter using
         * {@link #onBindViewHolder(ViewHolder, int, List)}. Since it will be re-used to display
         * different items in the data set, it is a good idea to cache references to sub views of
         * the View to avoid unnecessary {@link View#findViewById(int)} calls.
         *
         * @param parent   The ViewGroup into which the new View will be added after it is bound to
         *                 an adapter position.
         * @param viewType The view type of the new View.
         * @return A new ViewHolder that holds a View of the given view type.
         * @see #getItemViewType(int)
         * @see #onBindViewHolder(ViewHolder, int)
         */
        @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 vhItem(view);
        }

        /**
         * Called by RecyclerView to display the data at the specified position. This method should
         * update the contents of the {@link ViewHolder#itemView} to reflect the item at the given
         * position.
         * <p/>
         * Note that unlike {@link ListView}, RecyclerView will not call this method
         * again if the position of the item changes in the data set unless the item itself is
         * invalidated or the new position cannot be determined. For this reason, you should only
         * use the <code>position</code> parameter while acquiring the related data item inside
         * this method and should not keep a copy of it. If you need the position of an item later
         * on (e.g. in a click listener), use {@link ViewHolder#getAdapterPosition()} which will
         * have the updated adapter position.
         * <p/>
         * Override {@link #onBindViewHolder(ViewHolder, int, List)} instead if Adapter can
         * handle effcient partial bind.
         *
         * @param holder   The ViewHolder which should be updated to represent the contents of the
         *                 item at the given position in the data set.
         * @param position The position of the item within the adapter's data set.
         */
        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
            HashMap<String, Object> hmItem = new HashMap<String, Object>();
            hmItem = alHomehubList.get(position);
            vhItem vhItemView = (vhItem) holder;

            final String serialNumber = util.null2string(hmItem.get(Constants.MDNS_KEY_INFO_SERIAL_NUMBER));
            final String modelNumber = util.null2string(hmItem.get(Constants.MDNS_KEY_INFO_MDOEL_NUMBER));
            final String manufacturer = util.null2string(hmItem.get(Constants.MDNS_KEY_INFO_MANUFACTURER));
            final String profileVersion = util.null2string(hmItem.get(Constants.MDNS_KEY_INFO_PROFILE_VERSION));
            final String status = util.null2string(hmItem.get(Constants.MDNS_KEY_INFO_HOMEHUB_STATUS));
            final String deviceId = util.null2string(hmItem.get(Constants.HTTP_device_id));

            vhItemView.tvSerialNumber.setText(getString(R.string.layout_things_guide_31, serialNumber));
            vhItemView.tvModelName.setText(getString(R.string.layout_things_guide_32, modelNumber, manufacturer));
            if ( status.equalsIgnoreCase("NE") ) {
                vhItemView.ivHomehubIcon.setImageResource(R.drawable.img_homehub_icon_hub_enroll);
                vhItemView.tvHomehubStatus.setText(R.string.layout_things_guide_33);
            } else if (status.equalsIgnoreCase("E1")) {
                vhItemView.ivHomehubIcon.setImageResource(R.drawable.img_homehub_icon_hub_done);
                vhItemView.tvHomehubStatus.setText(R.string.layout_things_guide_34);
            } else {
                vhItemView.ivHomehubIcon.setVisibility(View.GONE);
                vhItemView.tvHomehubStatus.setVisibility(View.GONE);
            }

//            final HashMap<String, Object> finalHmItem = hmItem;
            vhItemView.llRoot.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if ( isLoading ) {
                        loadingAnimation.cancel();
                    }
                    if ( status.equalsIgnoreCase("NE") ) {
                        Intent intent = new Intent(act, Things_Homehub_Set_Password.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);
                        util.callActivityForResultNoAnim(act, intent, Constants.ACT_THINGS_HOMEHUB_SET_PASSWORD);
                    } else if ( status.equalsIgnoreCase("E1") ) {
                        Intent intent = new Intent(act, Things_Homehub_Assign_Password.class);
                        intent.putExtra(Constants.EXTRA_DEVICE_ID, deviceId);
                        util.callActivityForResultNoAnim(act, intent, Constants.ACT_THINGS_HOMEHUB_ASSIGN_PASSWORD);
                    }
//                    send_WS_device_register(finalHmItem);
                }
            });
        }

        /**
         * Returns the total number of items in the data set hold by the adapter.
         *
         * @return The total number of items in this adapter.
         */
        @Override
        public int getItemCount() {
            return alHomehubList.size();
        }
    }

    public class vhItem extends RecyclerView.ViewHolder {

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

        public vhItem(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);
        }
    }

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

        intent = new Intent();
        if ( resultCode == act.RESULT_OK ) {
            switch (requestCode) {
                case Constants.ACT_THINGS_HOMEHUB_SET_PASSWORD:

                    intent = new Intent();
                    setResult(RESULT_OK, intent);
                    finish();

                    break;
            }
        } else {
            switch (requestCode) {
                case Constants.ACT_THINGS_HOMEHUB_SET_PASSWORD:
//                    setResult(RESULT_CANCELED, intent);
//                    finish();
                    break;
            }
        }
    }

    @Override
    public void onBackPressed() {

        customDialog.MsgAlert(act, Constants.MSG905);
    }

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

        if ( isLoading ) {
            isDestroy = true;
            loadingAnimation.cancel();
        }
    }
}
