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

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.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.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

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

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

    /*통신 관련*/
    private static final int MSG_COM_P_DEVICES_PROPERTY_DEVICE_ID = 1;
    private int mType = 0;

    /*공통*/
    private Activity mActivity;
    private Intent mIntent;
    private Util mUtil = new Util();
    private CustomDialog mCustomDialog = new CustomDialog();
    private String mDeviceId = "";
    private String mDeviceName = "";
    private String mNodeId = "";

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

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

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

        if (getIntent() != null) {
            Intent intent = getIntent();
            mDeviceId = intent.getStringExtra(Constants.EXTRA_DEVICE_ID);
            mDeviceName = intent.getStringExtra(Constants.EXTRA_DEVICE_NAME);
            mNodeId = intent.getStringExtra(Constants.EXTRA_NODE_ID);
        }

        mUtil.getView(mActivity, R.id.llBtn1).setOnClickListener(this);
        mUtil.getView(mActivity, R.id.llBtn2).setOnClickListener(this);

        setDisp();
    }

    @Override
    public void onBackPressed() {

        mIntent = new Intent();
        mActivity.setResult(RESULT_CANCELED, mIntent);
        finish();
        return;
    }

    @Override
    public void resultCustomDialogResponse(int msgId, int btnResult) {

        switch (msgId) {

            case Constants.MSG998:
                mUtil.callApp_Start(mActivity, "LOGOUT");
                break;
            case Constants.MSG997:
                mUtil.callApp_Start(mActivity, "HOME_RELOAD");
                break;
            case Constants.MSG807:
                if (btnResult == 1) {
                    comHandler.sendMessageDelayed(comHandler.obtainMessage(mType),
                            Constants.HANDLER_DELAY_MILLIS);
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void onClick(View view) {

        switch (view.getId()) {
            case R.id.llBtn1:
                mDeviceName = mUtil.getEditTextVal(mActivity, R.id.edtName);
                if ("".equals(mDeviceName)) {
                    mCustomDialog.msgAlert(mActivity, Constants.MSG845);
                    return;
                }
                view.setEnabled(false);
                comHandler.sendMessageDelayed(
                        comHandler.obtainMessage(MSG_COM_P_DEVICES_PROPERTY_DEVICE_ID),
                        Constants.HANDLER_DELAY_MILLIS);
                break;
            case R.id.llBtn2:
                onBackPressed();
                break;
            default:
                break;
        }
    }

    /**
     * UI display.
     */
    private void setDisp() {
        LogUtil.i(TAG, "setDisp : mDeviceName : " + mDeviceName);
        mUtil.getTextView(mActivity, R.id.edtName).setText(mDeviceName);
        ((EditText) mUtil.getView(mActivity, R.id.edtName))
                .setSelection(((EditText) mUtil.getView(mActivity, R.id.edtName)).length());
    }

    /**
     * 장치 이름 또는 아이콘 변경을 요청한다.
     */
    private void sendPostDeviceProperty() {
        try {
            HttpSend httpSend;

            httpSend = new HttpSend(mActivity);

            httpSend.setOnDataSendToReslutEvent(new OnDataSendToReslut() {
                @Override
                public void resultResponse(Response result) {
                    resultPostDeviceProperty(result);
                }
            });
            httpSend.P_devices_property_device_id(mDeviceId, mNodeId, mDeviceName);

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 장치 이름 또는 아이콘 변경 요청 결과.
     *
     * @param rpResult 결과 data
     */
    private void resultPostDeviceProperty(Response rpResult) {
        try {
            if (rpResult.getStatusCode() == Response.OK) {
                mUtil.setShowToast(mActivity, mUtil.getString(mActivity, R.string.MSG843),
                        Toast.LENGTH_SHORT);
                mIntent = new Intent();
                mActivity.setResult(RESULT_OK, mIntent);
                finish();
            } else {
                JSONObject joResult = new JSONObject(rpResult.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.MSG000, errorMsg);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            mCustomDialog.msgAlert(mActivity, Constants.MSG807);
        }
    }

    Handler comHandler = new Handler(new IncomingHandlerCallBack());

    /**
     * 장치명 변경 요청 핸들러.
     */
    class IncomingHandlerCallBack implements Handler.Callback {

        @Override
        public boolean handleMessage(Message msg) {

            mType = msg.what;
            switch (msg.what) {
                case MSG_COM_P_DEVICES_PROPERTY_DEVICE_ID:
                    //dialog_show();
                    sendPostDeviceProperty();
                    break;

                default:
                    break;
            }
            return true;
        }
    }

}
