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

package com.ntels.onecable.view.join;

import com.ntels.onecable.R;
import com.ntels.onecable.common.AppConfig;
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.CustomActivity;
import com.ntels.onecable.common.widget.CustomScrollView;
import com.ntels.onecable.view.dialog.CustomDialog;

import org.json.JSONObject;

import android.app.Activity;
import android.app.DatePickerDialog;
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.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

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

    // 서버 API 요청 구분 코드
    private static final int MSG_COM_G_HOMEGRP_MEMBERS_QUIZ_LIST = 1;
    private static final int MSG_COM_P_MEMBER_INFO = 2;

    private static final String QUIZ_STATUS_CODE_MANUAL = "1";
    private static final String QUIZ_STATUS_CODE_SELECT = "2";

    Handler mComHandler = new Handler(new IncomingHandlerCallBack());
    private Util mUtil = new Util();
    private CustomDialog mCustomDialog = new CustomDialog();
    private Activity mActivity;
    private boolean mIsReloadFinish = false;
    private int mType = 0;
    private ArrayList<HashMap<String, Object>> mTotalList = new ArrayList<>();
    private String authorizationQuestion = "";
    private String mQuizAnswer = "";
    private LinearLayoutManager mLinearLayoutManager;
    private JoinStep3rdMasterMenuAdapter mJoinStep3rdMasterMenuAdapter;
    private ArrayList<HashMap<String, Object>> mQuizData = new ArrayList<HashMap<String, Object>>();
    private HashMap<String, Object> mSelectedQuiz = new HashMap<>();
    private boolean mIsQuizManualInput = false;
    private AppConfig mAppConfig;
    private Intent mIntent;
    private String mPhone = "";
    private String mCustId = "";
    private String mCtrtGrpId = "";

    @BindView(R.id.tvQuestion) TextView mQuestion;
    @BindView(R.id.llSlidingMenu) LinearLayout mSlidingMenu;
    @BindView(R.id.rcvList) RecyclerView mQuizList;
    @BindView(R.id.llQuiz) LinearLayout mQuizLayout;
    @BindView(R.id.edtQuiz) EditText mQuizEditText;
    @BindView(R.id.svBody) CustomScrollView mCustomScrollView;
    @BindView(R.id.llBtn1) LinearLayout mNextBtn;

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        mActivity = JoinStep3rdMaster.this;
        mAppConfig = (AppConfig) mActivity.getApplicationContext();
        mCustomDialog.setOnMsgAlterToResultEvent(this);

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

        // annotation 사용을 위해 bind.
        ButterKnife.bind(this);

        if (null != getIntent()) {
            mPhone = getIntent().getStringExtra(Constants.EXTRA_PHONE);
            mCustId = getIntent().getStringExtra(Constants.EXTRA_CUST_ID);
            mCtrtGrpId = getIntent().getStringExtra(Constants.EXTRA_CTRT_GRP_ID);
        }

        setToolbar();
        displayListView();
        mComHandler.sendMessageDelayed(mComHandler.obtainMessage(MSG_COM_G_HOMEGRP_MEMBERS_QUIZ_LIST), Constants.HANDLER_DELAY_MILLIS);
    }

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

    /**
     * UI display.
     */
    private void displayListView() {

        mUtil.getView(mActivity, R.id.llBtn1).setOnClickListener(this);
        mUtil.getView(mActivity, R.id.llBtn1).setEnabled(false);
        mUtil.getView(mActivity, R.id.llBtn2).setOnClickListener(this);
        mUtil.getView(mActivity, R.id.rlQuestion).setOnClickListener(this);
        mUtil.getView(mActivity, R.id.tvValueDate).setOnClickListener(this);

        mUtil.setKeyboardHide(mActivity, mUtil.getLinearLayout(mActivity, R.id.llSvbody));
        /*mUtil.getEditText(mActivity, R.id.edtCellphone)
                .setOnEditorActionListener(new TextView.OnEditorActionListener() {
                    @Override
                    public boolean onEditorAction(TextView view, int actionId, KeyEvent event) {

                        switch (actionId) {
                            case EditorInfo.IME_ACTION_DONE:
                                mUtil.getView(mActivity, R.id.btnAdd).performClick();
                                break;
                            default:
                                return false;
                        }
                        return false;
                    }
                });*/
        mQuizEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                enableOkBtn();
            }
        });
        mLinearLayoutManager = new LinearLayoutManager(this);
        mQuizList.setLayoutManager(mLinearLayoutManager);
        mJoinStep3rdMasterMenuAdapter = new JoinStep3rdMasterMenuAdapter(this, mQuizData, mQuizOnClickListener);
        mQuizList.setAdapter(mJoinStep3rdMasterMenuAdapter);
    }

    private View.OnClickListener mQuizOnClickListener = new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            mQuestion.setText(((TextView) view).getText());
            int position = mUtil.null2int(view.getTag());
            mSelectedQuiz = mQuizData.get(position);

            if (QUIZ_STATUS_CODE_MANUAL.equals(mSelectedQuiz.get(Constants.KEY_STATUS_CODE))) {
                // 퀴즈 직접 입력 선택 시
                mQuizLayout.setVisibility(View.VISIBLE);
                mCustomScrollView.post(new Runnable() {
                    @Override
                    public void run() {
                        mCustomScrollView.fullScroll(ScrollView.FOCUS_DOWN);
                    }
                });
                mIsQuizManualInput = true;

            } else {
                // 기존 정의되어 있는 퀴즈 선택 시
                mQuizLayout.setVisibility(View.GONE);
                mQuizEditText.setText("");
                mIsQuizManualInput = false;
            }
            showSlidingMenu();
            enableOkBtn();
        }
    };

    /**
     * 정답날짜 입력 시 날짜선택 다이얼로그 노출.
     */
    private void showDatePicker() {
        GregorianCalendar calendar = new GregorianCalendar();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DAY_OF_MONTH);
//        int hour = calendar.get(Calendar.HOUR_OF_DAY);
//        int minute = calendar.get(Calendar.MINUTE);

        new DatePickerDialog(mActivity, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker datePicker, int year, int month, int day) {

                String date = String.format("%d / %d / %d", year, month + 1, day);
                mUtil.getTextView(mActivity, R.id.tvValueDate).setText(date);
                Dlog.i("pick date = " + date);

                Calendar calendar1 = Calendar.getInstance();
                calendar1.set(year, month, day);
                SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyyMMdd");
                mQuizAnswer = dateFormatter.format(calendar1.getTime());
                Dlog.i("mQuizAnswer = " + mQuizAnswer);

                enableOkBtn();
            }
        }, year, month, day).show();
    }

    /**
     * 필수입력 조건을 모두 만족해야 확인 버튼 활성화.
     */
    private void enableOkBtn() {
        boolean isEnable = true;

//        isEnable &= mTotalList.size() > 0;
        isEnable &= mQuestion.getText().length() > 0;
        isEnable &= mQuizAnswer.length() > 0;
        if (mIsQuizManualInput) {
            isEnable &= mQuizEditText.length() > 0;
        }

        mNextBtn.setEnabled(isEnable);
    }

    /**
     * 하단에서 슬라이딩으로 올라오는 퀴즈 선택 메뉴 노출/숨김.
     */
    private void showSlidingMenu() {
        if (mSlidingMenu.getVisibility() == View.GONE) {

            Animation bottomUp = AnimationUtils.loadAnimation(this,
                    R.anim.bottom_up);

            mSlidingMenu.startAnimation(bottomUp);
            mSlidingMenu.setVisibility(View.VISIBLE);
        } else {

            Animation bottomDown = AnimationUtils.loadAnimation(this,
                    R.anim.bottom_down);

            mSlidingMenu.startAnimation(bottomDown);
            mSlidingMenu.setVisibility(View.GONE);
        }
    }

    @OnClick({R.id.btnClose, R.id.llSlidingMenu})
    public void clickClose() {
        showSlidingMenu();
    }

    @Override
    public void onClick(View view) {

//        mUtil.getView(mActivity, R.id.rlQuestion).clearFocus();
        switch (view.getId()) {
            case R.id.llBtn1:
//                view.setEnabled(false);
//                authorizationQuestion = mUtil.getTextViewVal(mActivity, R.id.tvQuestion);
//                mQuizAnswer = mUtil.delSpecialChar(mUtil.getTextViewVal(mActivity, R.id.tvValueDate));

                /*if (mTotalList.size() == 0) {
                    mUtil.setShowToast(mActivity, mUtil.getString(mActivity, R.string.MSG812), Toast.LENGTH_SHORT);
                    view.setEnabled(true);
                    return;
                }
                if ("".equals(authorizationQuestion)) {
                    mUtil.setShowToast(mActivity, mUtil.getString(mActivity, R.string.MSG886), Toast.LENGTH_SHORT);
                    view.setEnabled(true);
                    return;
                }
                if ("".equals(mQuizAnswer)) {
                    mUtil.setShowToast(mActivity, mUtil.getString(mActivity, R.string.MSG813), Toast.LENGTH_SHORT);
                    view.setEnabled(true);
                    return;
                }*/

                if (mIsQuizManualInput) {
                    mSelectedQuiz.put(Constants.KEY_QUIZ, mQuizEditText.getText().toString());
                }
                mIntent = new Intent(mActivity, JoinStep4th.class);
                mIntent.putExtra(Constants.EXTRA_SELECTED_QUIZ, mSelectedQuiz);
                mIntent.putExtra(Constants.EXTRA_QUIZ_ANSWER, mQuizAnswer);
                mIntent.putExtra(Constants.EXTRA_PHONE, mPhone);
                mIntent.putExtra(Constants.EXTRA_CUST_ID, mCustId);
                mIntent.putExtra(Constants.EXTRA_CTRT_GRP_ID, mCtrtGrpId);
                mIntent.putExtra(Constants.EXTRA_GRADE_CODE, Constants.GRADE_CODE_MAS);
                mUtil.callActivityForResult(mActivity, mIntent, Constants.ACT_JOIN_STEP_4TH);
//                mComHandler.sendMessageDelayed(mComHandler.obtainMessage(MSG_COM_P_MEMBER_INFO), Constants.HANDLER_DELAY_MILLIS);
                break;
            case R.id.llBtn2:
                onBackPressed();
                break;
            case R.id.rlQuestion:
                showSlidingMenu();
//                mUtil.getView(mActivity, R.id.rlQuestion).requestFocus();
                break;
            case R.id.tvValueDate:
                showDatePicker();
                /*DialogDate dp1 = new DialogDate(mActivity);
                dp1.setDateVal(mUtil.getTextViewVal(mActivity, R.id.tvValueDate));
                dp1.setTitle(mUtil.getString(mActivity, R.string.layout_homemember_add_06));
                dp1.setBtn1Val(mUtil.getString(mActivity, R.string.layout_ok));
                dp1.setBtn2Val(mUtil.getString(mActivity, 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();
                        mUtil.getTextView(mActivity, R.id.tvValueDate).setText(date);
                        enableOkBtn();
                    }

                    @Override
                    public void onCancelButton(Dialog dialog) {

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

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

                    resultGetHomegrpMemberQuizList(result);
                }
            });
            httpSend.getHomeGroupMembersQuizList();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    private void resultGetHomegrpMemberQuizList(Response result) {
        try {
            if (result.getStatusCode() == 200) {
                JSONObject joResult = new JSONObject(result.getContent());
                String quizList = mUtil.null2string(joResult.get(Constants.KEY_QUIZ_LIST));
                mQuizData = mUtil.jsonToArrayListMap(quizList);
                mJoinStep3rdMasterMenuAdapter.setData(mQuizData);
                mJoinStep3rdMasterMenuAdapter.notifyDataSetChanged();
            } else {
                JSONObject joResult = new JSONObject(result.getContent());
                Dlog.v(joResult.toString());
                String resultCode = mUtil.null2string(joResult.get(Constants.KEY_RESULT_CODE));
                String resultMsg = mUtil.null2string(joResult.get(Constants.KEY_RESULT_MSG));

                mCustomDialog.msgAlert(mActivity, Constants.MSG000, resultMsg);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            mCustomDialog.msgAlert(mActivity, Constants.MSG807);
        }
    }

    /**
     * 회원 정보 수정(인증퀴즈 변경 처리한다) 요청.
     */
    private void sendPutMemberInfo() {

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

                    resultPutMemberInfo(result);
                }
            });

            //공통 변수 입력
            httpSend.putChangeMemberInfo(Constants.KEY_QUIZ, mSelectedQuiz.get(Constants.KEY_QUIZ_ID).toString(),
                    mSelectedQuiz.get(Constants.KEY_QUIZ).toString(), mSelectedQuiz.get(Constants.KEY_STATUS_CODE).toString(),
                    mQuizAnswer);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

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

        try {
            if (response.getStatusCode() == 200) {

                mUtil.setShowToast(mActivity, mUtil.getString(mActivity, R.string.MSG927), Toast.LENGTH_SHORT);
                mIntent = new Intent();
                mActivity.setResult(RESULT_OK, mIntent);
                finish();
            } else {
                JSONObject joResult = new JSONObject(response.getContent());
                Dlog.v(joResult.toString());
                String resultCode = mUtil.null2string(joResult.get(Constants.KEY_RESULT_CODE));
                String resultMsg = mUtil.null2string(joResult.get(Constants.KEY_RESULT_MSG));

                mCustomDialog.msgAlert(mActivity, Constants.MSG000, resultMsg);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            mCustomDialog.msgAlert(mActivity, Constants.MSG807);
        }
        try {
            mNextBtn.setEnabled(true);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

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

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

    @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) {
                    mComHandler.sendMessageDelayed(mComHandler.obtainMessage(mType), Constants.HANDLER_DELAY_MILLIS);
                }
                break;
            case Constants.MSG887:
                mIsReloadFinish = true;
                setFinish();
                break;
            default:
                break;
        }
    }

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

    }

    /**
     * 화면 최하단으로 스크롤.
     */
    public void scrollToEnd() {

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

                mUtil.getScrollView(mActivity, R.id.svBody).fullScroll(View.FOCUS_DOWN);
            }
        });
    }

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

        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case Constants.ACT_JOIN_STEP_4TH:
                    mIntent = new Intent();
                    setResult(RESULT_OK, mIntent);
                    finish();
                    break;
                default:
                    break;
            }
        } else {
            onBackPressed();
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {

        super.onSaveInstanceState(outState);
    }

    @Override
    public void onBackPressed() {

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

    class IncomingHandlerCallBack implements Handler.Callback {

        @Override
        public boolean handleMessage(Message msg) {

            mType = msg.what;
            switch (msg.what) {
                case MSG_COM_G_HOMEGRP_MEMBERS_QUIZ_LIST:
                    sendGetHomegrpMembersQuizList();
                    break;
                case MSG_COM_P_MEMBER_INFO:
                    sendPutMemberInfo();
                    break;
                default:
                    break;
            }
            return true;
        }
    }
}
