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

package com.ntels.onecable.view.homemember;

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.Util;
import com.ntels.onecable.common.widget.CustomActionBarActivity;
import com.ntels.onecable.view.dialog.CustomDialog;
import com.ntels.onecable.view.dialog.DialogDate;

import org.json.JSONObject;

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.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 java.util.ArrayList;
import java.util.HashMap;

/**
 * <pre>
 * 1. ClassName :   HomeMemberAdd
 * 2. FileName  :   HomeMemberAdd.java
 * 3. Package   :   com.ntels.onecable.view.homemember
 * 4. Date      :   2016-12-01
 * 5. Author    :   aaron
 * 6. Comment   :   Initialize
 * </pre>
 */
public class HomeMemberAdd extends CustomActionBarActivity implements View.OnClickListener,
        CustomDialog.OnMsgAlterToResult {

    private static final int MSG_COM_P_HOMEGRP_MEMBERS = 1;
    private static final int MSG_COM_P_HOMEGRP_MEMBERS_VALIDATION = 2;
    Handler comHandler = new Handler(new IncomingHandlerCallBack());
    private Util util = new Util();
    private CustomDialog customDialog = new CustomDialog();
    private Activity act;
    private boolean isReloadFinish = false;
    private int type = 0;
    private ArrayList<HashMap<String, Object>> totalList = new ArrayList<>();
    private String authorizationQuestion = "";
    private String authorizationReply = "";

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        act = HomeMemberAdd.this;
        customDialog.setOnMsgAlterToResultEvent(this);

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

        setToolbar();
        displayListView();
    }

    /**
     * 툴바 셋팅.
     */
    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_homemember_add_01));
    }

    /**
     * UI display.
     */
    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.rlQuestion).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 view, int actionId, KeyEvent event) {

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

    @Override
    public void onClick(View view) {

        util.getView(act, R.id.rlQuestion).clearFocus();
        switch (view.getId()) {
            case R.id.llBtn1:
                view.setEnabled(false);
                authorizationQuestion = util.getEditTextVal(act, R.id.tvQuestion);
                authorizationReply = util.getTextViewVal(act, R.id.tvValueDate);

                if (totalList.size() == 0) {
                    util.setShowToast(act, util.getString(act, R.string.MSG812), Toast.LENGTH_SHORT);
                    view.setEnabled(true);
                    return;
                }
                if ("".equals(authorizationQuestion)) {
                    util.setShowToast(act, util.getString(act, R.string.MSG886), Toast.LENGTH_SHORT);
                    view.setEnabled(true);
                    return;
                }
                if ("".equals(authorizationReply)) {
                    util.setShowToast(act, util.getString(act, R.string.MSG813), Toast.LENGTH_SHORT);
                    view.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 (totalList.size() >= 10) {
                    util.setShowToast(act, util.getString(act, R.string.MSG811), Toast.LENGTH_SHORT);
                    return;
                }

                String targetEmail = util.getEditTextVal(act, R.id.edtEmail);
                if ("".equals(targetEmail)) {
                    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.rlQuestion:
                util.getView(act, R.id.rlQuestion).requestFocus();
                break;
            case R.id.tvValueDate:
                DialogDate dp1 = new DialogDate(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 DialogDate.DatePickerListner() {
                    @Override
                    public void onDoneButton(Dialog dialog, String date) {

                        dialog.dismiss();
                        util.getTextView(act, R.id.tvValueDate).setText(date);
                    }

                    @Override
                    public void onCancelButton(Dialog dialog) {

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

    /**
     * <pre>
     * 홈그룹 멤버 초대 유효성 체크 요청
     * 초대 대상자의 유효성을 체크한다
     * (홈허브가 없는 홈의 회원 또는 홈이 없는 회원/비회원만 가능).
     * </pre>
     */
    private void sendGetHomegrpMembersValidation() {

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

                    resultGetHomegrpMembersValidation(result);
                }
            });

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

    /**
     * {@link #sendGetHomegrpMembersValidation()} 요청 결과.
     *
     * @param response 결과 data
     */
    private void resultGetHomegrpMembersValidation(Response response) {

        try {
            if (response.getStatusCode() == 200) {
                String targetEmail = util.getEditTextVal(act, R.id.edtEmail);
                if ("".equals(targetEmail)) {
                    util.setShowToast(act, util.getString(act, R.string.MSG885), Toast.LENGTH_SHORT);
                    return;
                }
                String gradeCode = "SIM";
                HashMap<String, Object> tempMap = new HashMap<String, Object>();
                tempMap.put(Constants.KEY_TARGET_EMAIL, targetEmail);
                tempMap.put(Constants.KEY_GRADE_CODE, gradeCode);
                totalList.add(tempMap);
                util.getEditText(act, R.id.edtEmail).setText("");
                setDispContents();
                scrollToEnd();
            } else {
                JSONObject joResult = new JSONObject(response.getContent());
                Dlog.v(joResult.toString());
                String errorCode = util.null2string(joResult.get(Constants.KEY_ERR_CODE));
                String errorMsg = util.null2string(joResult.get(Constants.KEY_ERR_MSG));

                if (errorCode.equals("401")) {
                    customDialog.msgAlert(act, Constants.MSG998, errorMsg);
                } else if (errorCode.equals("401-106")) {
                    customDialog.msgAlert(act, Constants.MSG997, errorMsg);
                } else {
                    util.getEditText(act, R.id.edtEmail).requestFocus();
                    util.setShowToast(act, errorMsg, 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) {
            ex.printStackTrace();
        }
    }

    /**
     * 홈그룹 멤버 초대(홈그룹의 멤버를 초대한다) 요청.
     */
    private void sendPostHomegrpMembers() {

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

                    resultPostHomegrpMembers(result);
                }
            });

            HashMap<String, Object> tempMap = new HashMap<String, Object>();
            tempMap.put(Constants.KEY_AUTHORIZATION_QUESTION, authorizationQuestion);
            tempMap.put(Constants.KEY_AUTHORIZATION_REPLY, authorizationReply);
            tempMap.put(Constants.KEY_INVITATION_LIST, totalList);

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

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

    /**
     * {@link #sendPostHomegrpMembers()} 요청 결과.
     *
     * @param response 결과 data
     */
    private void resultPostHomegrpMembers(Response response) {

        try {
            if (response.getStatusCode() == 200) {
                //종료 reload 하도록
                util.setShowToast(act, util.getString(act, R.string.MSG887), Toast.LENGTH_SHORT);
                isReloadFinish = true;
                setFinish();
            } else {
                JSONObject joResult = new JSONObject(response.getContent());
                Dlog.v(joResult.toString());
                String errorCode = util.null2string(joResult.get(Constants.KEY_ERR_CODE));
                String errorMsg = util.null2string(joResult.get(Constants.KEY_ERR_MSG));

                switch (errorCode) {
                    case "401":
                        customDialog.msgAlert(act, Constants.MSG998, errorMsg);
                        break;
                    case "401-106":
                        customDialog.msgAlert(act, Constants.MSG997, errorMsg);
                        break;
                    default:
                        util.setShowToast(act, errorMsg, Toast.LENGTH_SHORT);
                        break;
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            customDialog.msgAlert(act, Constants.MSG807);
        }
        try {
            util.getView(act, R.id.llBtn1).setEnabled(true);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * Activity 종료 처리.
     */
    private void setFinish() {

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

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

        switch (msgId) {
            case Constants.MSG998:
                util.callApp_Start(act, "LOGOUT");
                break;
            case Constants.MSG997:
                util.callApp_Start(act, "HOME_RELOAD");
                break;
            case Constants.MSG807:
                if (btnResult == 1) {
                    comHandler.sendMessageDelayed(comHandler.obtainMessage(type), 10);
                }
                break;
            default:
                break;
        }
    }

    /**
     * UI dislplay.
     */
    void setDispContents() {

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

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

            String tempTargetEmail = util.null2string(totalList.get(row).get(Constants.KEY_TARGET_EMAIL));
            util.getTextView(viewChild, R.id.tvEmail).setText(tempTargetEmail);
            util.getView(viewChild, R.id.btnDel).setTag(row);
            util.getView(viewChild, R.id.btnDel).setOnClickListener(new View.OnClickListener() {
                int tag = 0;

                @Override
                public void onClick(View view) {

                    tag = (int) view.getTag();
                    totalList.remove(tag);
                    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);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case Constants.ACT_HOMEMEMBER_ADD_EMAIL:
                    HashMap<String, Object> tempMap = new HashMap<String, Object>();
                    String targetEmail = util.null2string(data.getStringExtra(Constants.KEY_TARGET_EMAIL));
                    String gradeCode = util.null2string(data.getStringExtra(Constants.KEY_GRADE_CODE));
                    String extraPosition = util.null2string(data.getStringExtra(Constants.EXTRA_POSITION));
                    tempMap.put(Constants.KEY_TARGET_EMAIL, targetEmail);
                    tempMap.put(Constants.KEY_GRADE_CODE, gradeCode);
                    if (extraPosition.equals("")) {
                        totalList.add(tempMap);
                    } else {
                        totalList.set(util.null2int(extraPosition), tempMap);
                    }

                    setDispContents();
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {

        super.onSaveInstanceState(outState);
    }

    @Override
    public void onBackPressed() {

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

    class IncomingHandlerCallBack implements Handler.Callback {

        @Override
        public boolean handleMessage(Message msg) {

            type = msg.what;
            switch (msg.what) {
                case MSG_COM_P_HOMEGRP_MEMBERS:
                    sendPostHomegrpMembers();
                    ;
                    break;
                case MSG_COM_P_HOMEGRP_MEMBERS_VALIDATION:
                    sendGetHomegrpMembersValidation();
                    break;
                default:
                    break;
            }
            return true;
        }
    }
}
