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

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

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.TextView;
import android.widget.Toast;

import com.ntels.kneet.v3.common.AppConfig;
import com.ntels.kneet.v3.common.Constants;
import com.ntels.kneet.v3.common.http.HttpSend;
import com.ntels.kneet.v3.common.http.Response;
import com.ntels.kneet.v3.common.c_interface.Main_Interface;
import com.ntels.kneet.v3.common.c_interface.OnDataSendToReslut;
import com.ntels.kneet.v3.common.util.Dlog;
import com.ntels.kneet.v3.common.util.Util;
import com.ntels.kneet.v3.common.widget.CustomActionBarActivity;
import com.ntels.kneet.v3.R;
import com.ntels.kneet.v3.view.dialog.CustomDialog;
import com.ntels.kneet.v3.view.dialog.Dialog_Date;

import org.json.JSONObject;

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

public class HomeMember_Add extends CustomActionBarActivity implements View.OnClickListener,
                                                                       CustomDialog.OnMsgAlterToResult {

    /** Called when the activity is first created. */

    private Toolbar   toolbar;
    private AppConfig appConfig;
    Main_Interface mCallback;
    private Util util = new Util();
    private CustomDialog customDialog = new CustomDialog();
    private Intent   intent;
    private Activity act;
    private boolean bReloadFinishFlag = false;

    private              int iType                                = 0;
    private static final int MSG_COM_P_HOMEGRP_MEMBERS            = 1;
    private static final int MSG_COM_P_HOMEGRP_MEMBERS_VALIDATION = 2;
    private RecyclerView rcvList;
    private ArrayList<HashMap<String, Object>> alTotalList = new ArrayList<HashMap<String, Object>>();
    private boolean                            loading     = false;
    LinearLayoutManager mLayoutManager;
    private String sCallType               = "";
    private String sAUTHORIZATION_QUESTION = "";
    private String sAUTHORIZATION_REPLY    = "";

    /**
     * <PRE>
     * 1. MethodName: onCreate
     * 2. ClassName :
     * 3. Comment   : onCreate
     * 4. Developer : 최진오
     * 5. Created   : 2015. 10.
     * </PRE>
     */
    @Override public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        act = HomeMember_Add.this;
        appConfig = (AppConfig) act.getApplicationContext();
        customDialog.setOnMsgAlterToResultEvent(this);

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

        this.setContentView(viewToLoad);
        String sTempHour = "";
        if ( savedInstanceState != null ) {

        } else {
            Intent intent = getIntent();
            sCallType = util.null2string(intent.getStringExtra(Constants.EXTRA_CALL_TYPE));
            //            sDate = util.null2string(intent.getStringExtra(Constants.EXTRA_DATE));
        }
        setToolbar();

        displayListView();
    }

    private void setToolbar() {

        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_homemember_add_01));
    }

    private void displayListView() {

        util.getView(act, R.id.llBtn1).setOnClickListener(this);
        util.getView(act, R.id.llBtn2).setOnClickListener(this);
        util.getView(act, R.id.btnAdd).setOnClickListener(this);
        util.getView(act, R.id.tvValueDate).setOnClickListener(this);

        util.setKeyboardHide(act, util.getLinearLayout(act, R.id.llSvbody));
        util.getEditText(act, R.id.edtEmail).setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {

                switch (actionId) {
                    case EditorInfo.IME_ACTION_DONE:
                        util.getView(act, R.id.btnAdd).performClick();
                        break;
                    default:
                        return false;
                }
                return false;
            }
        });
        int iLayout = 0;

        //        util.getEditText(act, R.id.edtEmail).requestFocus();
        //        util.setKeyboardShow(act, util.getEditText(act, R.id.edtEmail));
        //        util.getEditText(act, R.id.edtEmail).setOnFocusChangeListener(new View.OnFocusChangeListener() {
        //            public void onFocusChange(View v, boolean hasFocus) {
        //
        //                if ( hasFocus ) {
        //                    act.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE|WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        //                }
        //            }
        //        });
        //        util.getEditText(act, R.id.edtEmail).requestFocus();
        //        util.setKeyboardShow(act, util.getEditText(act, R.id.edtEmail));
    }

    @Override public void onClick(View v) {

        switch (v.getId()) {
            case R.id.llBtn1:
                v.setEnabled(false);
                sAUTHORIZATION_QUESTION = util.getEditTextVal(act, R.id.edtTitle);
                sAUTHORIZATION_REPLY = util.getTextViewVal(act, R.id.tvValueDate);

                if ( alTotalList.size() == 0 ) {
                    util.setShowToast(act, util.getString(act, R.string.MSG812), Toast.LENGTH_SHORT);
                    v.setEnabled(true);
                    return;
                }
                if ( "".equals(sAUTHORIZATION_QUESTION) ) {
                    util.setShowToast(act, util.getString(act, R.string.MSG886), Toast.LENGTH_SHORT);
                    v.setEnabled(true);
                    return;
                }
                if ( "".equals(sAUTHORIZATION_REPLY) ) {
                    util.setShowToast(act, util.getString(act, R.string.MSG813), Toast.LENGTH_SHORT);
                    v.setEnabled(true);
                    return;
                }

                ComHandler.sendMessageDelayed(ComHandler.obtainMessage(MSG_COM_P_HOMEGRP_MEMBERS), 10);
                break;
            case R.id.llBtn2:
                onBackPressed();
                break;
            case R.id.btnAdd:
                if ( alTotalList.size() >= 10 ) {
                    util.setShowToast(act, util.getString(act, R.string.MSG811), Toast.LENGTH_SHORT);
                    return;
                }

                String sHTTP_target_email = util.getEditTextVal(act, R.id.edtEmail);
                if ( "".equals(sHTTP_target_email) ) {
                    util.setShowToast(act, util.getString(act, R.string.MSG885), Toast.LENGTH_SHORT);
                    return;
                }

                ComHandler.sendMessageDelayed(ComHandler.obtainMessage(MSG_COM_P_HOMEGRP_MEMBERS_VALIDATION), 10);

                break;

            case R.id.tvValueDate:
                Dialog_Date dp1 = new Dialog_Date(act);
                dp1.setDateVal(util.getTextViewVal(act, R.id.tvValueDate));
                dp1.setTitle(util.getString(act, R.string.layout_homemember_add_06));
                dp1.setBtn1Val(util.getString(act, R.string.layout_ok));
                dp1.setBtn2Val(util.getString(act, R.string.layout_cancel));
                dp1.setMinDateVal("1900-01-01");
                dp1.setMaxDateVal("2100-12-31");
                dp1.setDtpVal(new Dialog_Date.DatePickerListner() {
                    @Override public void OnDoneButton(Dialog datedialog, String sDateVal) {

                        datedialog.dismiss();
                        util.getTextView(act, R.id.tvValueDate).setText(sDateVal);
                    }

                    @Override public void OnCancelButton(Dialog datedialog) {

                        datedialog.dismiss();
                    }
                });
                dp1.init();
                dp1.show();
                break;
            default:
                break;
        }
    }

    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_P_HOMEGRP_MEMBERS:
                    send_P_homegrp_members();
                    ;
                    break;
                case MSG_COM_P_HOMEGRP_MEMBERS_VALIDATION:
                    send_P_homegrp_members_validation();
                    break;
                default:
                    break;
            }
            return true;
        }
    }

    private void send_P_homegrp_members_validation() {

        try {
            HttpSend httpSend;
            httpSend = new HttpSend(act);
            httpSend.setOnDataSendToReslutEvent(new OnDataSendToReslut() {
                @Override public void resultResponse(Response result) {

                    result_P_homegrp_members_validation(result);
                }
            });

            httpSend.P_homegrp_members_validation(util.getEditTextVal(act, R.id.edtEmail));
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    private void result_P_homegrp_members_validation(Response rpResult) {

        try {
            if ( rpResult.getStatusCode() == 200 ) {
                String sHTTP_target_email = util.getEditTextVal(act, R.id.edtEmail);
                if ( "".equals(sHTTP_target_email) ) {
                    util.setShowToast(act, util.getString(act, R.string.MSG885), Toast.LENGTH_SHORT);
                    return;
                }
                String sHTTP_grade_code = "SIM";
                HashMap<String, Object> hmTemp = new HashMap<String, Object>();
                hmTemp.put(Constants.HTTP_target_email, sHTTP_target_email);
                hmTemp.put(Constants.HTTP_grade_code, sHTTP_grade_code);
                alTotalList.add(hmTemp);
                util.getEditText(act, R.id.edtEmail).setText("");
                setDispContents();
                scrollToEnd();
            } 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 {
                    //                    util.getEditText(act, R.id.edtEmail).requestFocus();
                    //                    util.setKeyboardShow(act, util.getEditText(act, R.id.edtEmail));
                    util.getEditText(act, R.id.edtEmail).requestFocus();
                    util.setShowToast(act, sERR_MSG, Toast.LENGTH_SHORT);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            customDialog.MsgAlert(act,Constants.MSG807);
        }
        try {
            util.getView(act, R.id.llBtn1).setEnabled(true);
        } catch (Exception ex) {

        }
    }

    private void send_P_homegrp_members() {

        try {
            HttpSend httpSend;
            httpSend = new HttpSend(act);
            httpSend.setOnDataSendToReslutEvent(new OnDataSendToReslut() {
                @Override public void resultResponse(Response result) {

                    result_P_homegrp_members(result);
                }
            });

            HashMap<String, Object> hmTemp = new HashMap<String, Object>();
            hmTemp.put(Constants.HTTP_authorization_question, sAUTHORIZATION_QUESTION);
            hmTemp.put(Constants.HTTP_authorization_reply, sAUTHORIZATION_REPLY);
            hmTemp.put(Constants.HTTP_invitation_list, alTotalList);

            Dlog.v(util.MapToJson(hmTemp));

            httpSend.P_homegrp_members(util.MapToJson(hmTemp));
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    private void result_P_homegrp_members(Response rpResult) {

        try {
            if ( rpResult.getStatusCode() == 200 ) {
                //종료 reload 하도록
                util.setShowToast(act, util.getString(act, R.string.MSG887), Toast.LENGTH_SHORT);
                bReloadFinishFlag = true;
                SetFinish();
            } 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 {
                    util.setShowToast(act, sERR_MSG, Toast.LENGTH_SHORT);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            customDialog.MsgAlert(act,Constants.MSG807);
        }
        try {
            util.getView(act, R.id.llBtn1).setEnabled(true);
        } catch (Exception ex) {

        }
    }

    private void SetFinish() {

        Intent intent = new Intent();
        intent.putExtra(Constants.EXTRA_RELOAD_FLAG, bReloadFinishFlag);
        this.setResult(RESULT_OK, intent);
        finish();
    }

    @Override public void resultCustomDialogResponse(int iMsgID, int iBtnResult) {

        switch (iMsgID) {
            case Constants.MSG998:
                util.callApp_Start(act, "LOGOUT");
                break;
            case Constants.MSG997:
                util.callApp_Start(act, "HOME_RELOAD");
                break;
            case Constants.MSG807:
                if ( iBtnResult == 1 ) {
                    ComHandler.sendMessageDelayed(ComHandler.obtainMessage(iType), 10);
                }
                break;
            default:
                break;
        }
    }

    void setDispContents() {

        util.getLinearLayout(act, R.id.llContents).removeAllViews();

        for ( int iRow = 0; iRow < alTotalList.size(); iRow++ ) {
            View viewChild = (View) View.inflate(act, R.layout.row_homemember_add_list, null);

            String sTempHTTP_target_email = util.null2string(alTotalList.get(iRow).get(Constants.HTTP_target_email));
            String sTempHTTP_grade_code = util.null2string(alTotalList.get(iRow).get(Constants.HTTP_grade_code));
            util.getTextView(viewChild, R.id.tvEmail).setText(sTempHTTP_target_email);
            util.getView(viewChild, R.id.btnDel).setTag(iRow);
            util.getView(viewChild, R.id.btnDel).setOnClickListener(new View.OnClickListener() {
                int iTag = 0;
                private Intent intent;

                @Override public void onClick(View v) {

                    iTag = (int) v.getTag();
                    alTotalList.remove(iTag);
                    setDispContents();
                }
            });
            util.getLinearLayout(act, R.id.llContents).addView(viewChild);
        }
    }

    public void scrollToEnd() {

        util.getScrollView(act, R.id.svBody).post(new Runnable() {
            @Override public void run() {

                util.getScrollView(act, R.id.svBody).fullScroll(View.FOCUS_DOWN);
            }
        });
    }
    @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {

        super.onActivityResult(requestCode, resultCode, data);
        Boolean bReload_Flag = false;
        if ( resultCode == act.RESULT_OK ) {
            switch (requestCode) {
                case Constants.ACT_HOMEMEMBER_ADD_EMAIL:
                    HashMap<String, Object> hmTemp = new HashMap<String, Object>();
                    String sHTTP_target_email = util.null2string(data.getStringExtra(Constants.HTTP_target_email));
                    String sHTTP_grade_code = util.null2string(data.getStringExtra(Constants.HTTP_grade_code));
                    String sEXTRA_POSITION = util.null2string(data.getStringExtra(Constants.EXTRA_POSITION));
                    hmTemp.put(Constants.HTTP_target_email, sHTTP_target_email);
                    hmTemp.put(Constants.HTTP_grade_code, sHTTP_grade_code);
                    if ( sEXTRA_POSITION.equals("") ) {
                        alTotalList.add(hmTemp);
                    } else {
                        alTotalList.set(util.null2int(sEXTRA_POSITION), hmTemp);
                    }

                    setDispContents();
                    break;
            }
        } else {
            //            switch (requestCode) {
            //                case Constants.ACT_HOMEMEMBER_DETAIL:
            //                case Constants.ACT_HOMEMEMBER_ADD:
            //                    bReload_Flag = data.getBooleanExtra(Constants.EXTRA_RELOAD_FLAG, false);
            //                    if ( bReload_Flag ) {
            //                        ComHandler.sendMessageDelayed(ComHandler.obtainMessage(MSG_COM_HOMEGRP_MEMBERS), 10);
            //                    }
            //                    break;
            //            }
            // if (appConfig.getGoErr()) {
            // act.setResult(act.RESULT_CANCELED, new Intent());
            // finish();
            // }
        }
    }

    @Override protected void onSaveInstanceState(Bundle outState) {

        super.onSaveInstanceState(outState);
    }

    /**
     * <PRE>
     * 1. MethodName: onBackPressed
     * 2. ClassName :
     * 3. Comment   : 뒤로가기 버튼
     * 4. Developer : 최진오
     * 5. Created   : 2015. 10.
     * </PRE>
     */
    @Override public void onBackPressed() {

        Intent intent = new Intent();
        intent.putExtra(Constants.EXTRA_RELOAD_FLAG, bReloadFinishFlag);
        this.setResult(RESULT_CANCELED, intent);
        finish();
    }
}
