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

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

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
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 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.List_Interface;
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.http.HttpSend;
import com.ntels.kneet.v3.common.http.Response;
import com.ntels.kneet.v3.common.util.Dlog;
import com.ntels.kneet.v3.common.util.Util;
import com.ntels.kneet.v3.common.util.recyclerview.DividerItemDecoration;
import com.ntels.kneet.v3.common.widget.CustomActionBarActivity;
import com.ntels.kneet.v3.view.Intro;
import com.ntels.kneet.v3.view.dialog.CustomDialog;
import com.ntels.kneet.v3.view.invitation.Invitation_List;

import org.json.JSONObject;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;

import jp.wasabeef.recyclerview.adapters.AlphaInAnimationAdapter;
import jp.wasabeef.recyclerview.adapters.ScaleInAnimationAdapter;

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

    private AppConfig appConfig;
    Main_Interface mCallback;
    private Util         util         = new Util();
    private CustomDialog customDialog = new CustomDialog();
    private Intent   intent;
    private Activity act;
    private              int                                iType                      = 0;
    private              DecimalFormat                      decimalFormat              = new DecimalFormat("00");
    private              ArrayList<HashMap<String, Object>> alTotalList                = new ArrayList<HashMap<String, Object>>();
    private static final int                                MSG_COM_G_NOTICES_PERSONAL = 1;
    private Message_Center_Adapter dataAdapter;
    private RecyclerView           rcvList;
    private SwipeRefreshLayout     swipeRefreshLayout;
    private GridLayoutManager      glmList;
    private LinearLayoutManager    llmList;
    private boolean loading         = false;
    private boolean bListHeader     = false;
    private boolean bListFooter     = false;
    private int     iListColumnsCnt = 1;
    private boolean bListFooterAnd  = false;

    private int firstVisibleItem, visibleItemCount, totalItemCount;
    private Toolbar toolbar;
    private int iMemberCnt     = 0;
    private int iInvitationCnt = 0;

    private ArrayList<HashMap<String, Object>> alList_Item_Sub              = new ArrayList<HashMap<String, Object>>();
    private HashMap<String, Object>            hmItem_Sub                   = new HashMap<String, Object>();
    private ArrayList<HashMap<String, Object>> alList_Invitation            = new ArrayList<HashMap<String, Object>>();
    private String                             sHTTP_item_name              = "";
    private String                             sHTTP_item_sub_type_code     = "";
    private String                             sHTTP_source_id              = "";
    private String                             sHTTP_source_sub_id          = "";
    private String                             sHTTP_condition_type_code    = "";
    private String                             sHTTP_cmdcls_value           = "";
    private String                             sPASSWORD                    = "";
    private String                             sEMAIL_ID                    = "";
    private String                             sSelectItem                  = "";
    private int                                iSelectPosition              = 0;
    private String                             sHTTP_nickname               = "";
    private String                             sHTTP_homegrp_id             = "";
    private String                             sHTTP_status_code            = "";
    private String                             sHTTP_target_email           = "";
    private String                             sHTTP_authorization_reply    = "";
    private String                             sHTTP_homegrp_name           = "";
    private String                             sHTTP_authorization_question = "";
    private String                             sHTTP_error_count            = "";
    private String                             sSearch_Type                 = "";
    private String                             sHist_id                     = "";
    private String                             sMaxHist_id                  = "";
    private String                             sMinHist_id                  = "";
    private boolean                            bMore                        = true;

    private boolean bReloadFinishFlag = false;

    @Override protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        act = Message_Center.this;
        appConfig = (AppConfig) act.getApplicationContext();
        customDialog.setOnMsgAlterToResultEvent(this);
        View viewToLoad = LayoutInflater.from(act).inflate(R.layout.message_center, null);

        this.setContentView(viewToLoad);

        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.VISIBLE);
        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_message_center_01));
        util.getTextView(toolbar, R.id.tvToolbarTitle2).setText("");
    }

    private void displayListView() {

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

        swipeRefreshLayout = (SwipeRefreshLayout) act.findViewById(R.id.swiperefreshlayou);
        swipeRefreshLayout.setColorSchemeResources(android.R.color.holo_red_light, android.R.color.holo_green_light, android.R.color.holo_blue_bright, android.R.color.holo_orange_light);
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override public void onRefresh() {

                if ( !dataAdapter.getListCheck() ) {
                    if ( !loading ) {
                        loading = true;
                        sSearch_Type = "";
                        sHist_id = "";
                        ComHandler.sendMessageDelayed(ComHandler.obtainMessage(MSG_COM_G_NOTICES_PERSONAL), 10);
                    }
                } else {
                    swipeRefreshLayout.setRefreshing(false);
                }
            }
        });
        setRefresh(true);
        loading = false;

        dataAdapter = new Message_Center_Adapter(act, 0, R.layout.row_message_center_list, R.layout.row_footer_add, alTotalList, this);
        dataAdapter.setListCheck(false);
        dataAdapter.setHeaderCheck(false);
        dataAdapter.setFooterCheck(true);

        rcvList = (RecyclerView) act.findViewById(R.id.rcvList);
        rcvList.setHasFixedSize(true);
        iListColumnsCnt = 1;
        if ( iListColumnsCnt == 1 ) {
            llmList = new LinearLayoutManager(act);
            rcvList.setLayoutManager(llmList);
        } else {
            glmList = new GridLayoutManager(act, iListColumnsCnt, GridLayoutManager.VERTICAL, false);
            glmList.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
                @Override public int getSpanSize(int position) {

                    int iPositionType = dataAdapter.getItemViewType(position);
                    int iTotalConut = dataAdapter.getItemCount();
                    int iValueConut = dataAdapter.getItemCount();
                    if ( bListHeader ) {
                        iValueConut = iTotalConut - 1;
                    }

                    if ( iPositionType == dataAdapter.TYPE_HEADER ) {
                        return glmList.getSpanCount();
                    } else {
                        return dataAdapter.getItemViewType(position) == 1 ? 1 : (iValueConut % iListColumnsCnt == 1 ? glmList.getSpanCount() : 1);
                    }
                }
            });
            rcvList.setLayoutManager(glmList);
        }
        rcvList.addItemDecoration(new DividerItemDecoration(act, R.drawable.list_color_section_01, true, false));
        //        rcvList.setItemAnimator(new FadeInAnimator());
        //        rcvList.setAdapter(dataAdapter);
        AlphaInAnimationAdapter alphaAdapter = new AlphaInAnimationAdapter(dataAdapter);
        alphaAdapter.setDuration(150);
        ScaleInAnimationAdapter scaleAdapter = new ScaleInAnimationAdapter(alphaAdapter);
        scaleAdapter.setDuration(150);
        rcvList.setAdapter(scaleAdapter);

        rcvList.setOnScrollListener(new RecyclerView.OnScrollListener() {

            @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) {

                super.onScrolled(recyclerView, dx, dy);
            }

            @Override public void onScrollStateChanged(RecyclerView recyclerView, int newState) {

                int totalItemCount = 0;
                int lastVisibleItem = 0;
                if ( iListColumnsCnt == 1 ) {
                    totalItemCount = llmList.getItemCount();
                    lastVisibleItem = llmList.findLastVisibleItemPosition();
                } else {
                    totalItemCount = glmList.getItemCount();
                    lastVisibleItem = glmList.findLastVisibleItemPosition();
                }
                if ( lastVisibleItem >= totalItemCount - 1 ) {
                    // 더보기 조회 중일때?
                    if ( !loading ) {
                        if ( bMore ) {
                            loading = true;
                            sSearch_Type = "D";
                            sHist_id = sMinHist_id;

                            HashMap<String, Object> hmTemp = new HashMap<String, Object>();
                            hmTemp.put(Constants.HTTP_MORE_YN, "Y");
                            alTotalList.set(alTotalList.size() - 1, hmTemp);
                            dataAdapter.notifyDataSetChanged();

                            ComHandler.sendMessageDelayed(ComHandler.obtainMessage(MSG_COM_G_NOTICES_PERSONAL), 10);
                        }
                    }
                }
            }
        });

        ComHandler.sendMessageDelayed(ComHandler.obtainMessage(MSG_COM_G_NOTICES_PERSONAL), 10);
    }

    private void setRefresh(boolean bVal) {

        if ( bVal ) {
            swipeRefreshLayout.setEnabled(true);
        } else {
            swipeRefreshLayout.setEnabled(false);
        }
    }
    private void setBadgeClear() {

        int iBadgeCnt = 0;
        util.setPreferences(getApplicationContext(), "badge_count", iBadgeCnt + "");
        Intent intent = new Intent("android.intent.action.BADGE_COUNT_UPDATE");
        // 패키지 네임과 클래스 네임 설정
        intent.putExtra("badge_count_package_name", getPackageName());
        intent.putExtra("badge_count_class_name", Intro.class.getCanonicalName());
        // 업데이트 카운트 클리어
        intent.putExtra("badge_count", iBadgeCnt);
        sendBroadcast(intent);
    }

    @Override public void onClick(View v) {

        switch (v.getId()) {
            case R.id.llBtn1:
                onBackPressed();
                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_G_NOTICES_PERSONAL:
                    send_G_notices_personal();
                    break;
                //                case MSG_COM_HOMEGRPS:
                //                    send_homegrps();
                //                    break;
                default:
                    break;
            }
            return true;
        }
    }

    private void send_G_notices_personal() {

        try {
            HttpSend httpSend;
            if ( sSearch_Type.equals("D") ) {
                httpSend = new HttpSend(act, false);
            } else {
                httpSend = new HttpSend(act, !swipeRefreshLayout.isRefreshing());
            }
            httpSend.setOnDataSendToReslutEvent(new OnDataSendToReslut() {
                @Override public void resultResponse(Response result) {

                    result_G_notices_personal(result);
                }
            });
            httpSend.G_notices_personal(sHist_id, sSearch_Type);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    private void result_G_notices_personal(Response rpResult) {

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

                JSONObject joResult = new JSONObject(rpResult.getContent());
                Dlog.v(joResult.toString());

                //회원 번호
                String sHTTP_push_count = util.null2string(joResult.get(Constants.HTTP_push_count));
                String sHTTP_push_list = util.null2string(joResult.get(Constants.HTTP_push_list));

                ArrayList<HashMap<String, Object>> alList = util.jsonToArrayListMap(sHTTP_push_list);

                if ( sSearch_Type.equals("") ) {
                    alTotalList.clear();
                    setBadgeClear();
                    util.getTextView(toolbar, R.id.tvToolbarTitle2).setText(sHTTP_push_count);
                }
                if ( alList.size() > 0 ) {
                    swipeRefreshLayout.setVisibility(View.VISIBLE);
                    util.getView(act, R.id.llNodata1).setVisibility(View.GONE);
                    if ( alTotalList.size() == 0 ) {
                        HashMap<String, Object> hmTemp = new HashMap<String, Object>();
                        hmTemp.put(Constants.HTTP_MORE_YN, "N");
                        alTotalList.add(hmTemp);
                    } else {
                        HashMap<String, Object> hmTemp = new HashMap<String, Object>();
                        hmTemp.put(Constants.HTTP_MORE_YN, "N");
                        alTotalList.set(alTotalList.size() - 1, hmTemp);
                    }
                    for ( int iRow = 0; iRow < alList.size(); iRow++ ) {
                        HashMap<String, Object> hmTemp = new HashMap<String, Object>();
                        hmTemp = alList.get(iRow);
                        String sHTTP_push_hist_id = hmTemp.get(Constants.HTTP_push_noti_hist_id).toString();
                        if ( sMinHist_id.equals("") ) {
                            sMinHist_id = sHTTP_push_hist_id;
                        } else if ( util.str2long(sMinHist_id) > util.str2long(sHTTP_push_hist_id) ) {
                            sMinHist_id = sHTTP_push_hist_id;
                        }
                        if ( util.str2long(sMaxHist_id) < util.str2long(sHTTP_push_hist_id) ) {
                            sMaxHist_id = sHTTP_push_hist_id;
                        }

                        if ( sSearch_Type.equals("U") ) {
                            alTotalList.add(iRow, hmTemp);
                        } else {
                            alTotalList.add(alTotalList.size() - 1, hmTemp);
                        }
                    }
                } else {
                    if ( alTotalList.size() == 0 ) {
                        swipeRefreshLayout.setVisibility(View.GONE);
                        util.getView(act, R.id.llNodata1).setVisibility(View.VISIBLE);
                    } else {
                        HashMap<String, Object> hmTemp = new HashMap<String, Object>();
                        hmTemp.put(Constants.HTTP_MORE_YN, "N");
                        alTotalList.set(alTotalList.size() - 1, hmTemp);
                    }
                    if ( sSearch_Type.equals("D") ) {
                        bMore = false;
                    }
                }
                loading = false;
                dataAdapter.notifyDataSetChanged();
                swipeRefreshLayout.setRefreshing(false);
            } 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 {
                    customDialog.MsgAlert(act, Constants.MSG000, sERR_MSG);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            customDialog.MsgAlert(act, Constants.MSG807, "");
        }
    }

    @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);
                } else {
                    act.onBackPressed();
                }
                break;
            default:
                break;
        }
    }

    @Override protected void onSaveInstanceState(Bundle outState) {

        super.onSaveInstanceState(outState);
    }

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

        intent = new Intent();
        act.setResult(RESULT_CANCELED, intent);
        finish();
    }

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

        super.onActivityResult(requestCode, resultCode, data);
        String sCALL_TYPE = "";
        if ( resultCode == RESULT_OK ) {
            switch (requestCode) {
                case Constants.ACT_INVITATION_LIST:
                    util.callApp_Start(act, "HOME_RELOAD");
                    break;
                case Constants.ACT_HOME_START:
                    intent = new Intent();
                    act.setResult(RESULT_OK, intent);
                    finish();
                    break;
            }
        } else {
            if ( appConfig.getGoErr() ) {
                act.setResult(RESULT_CANCELED, new Intent());
                finish();
            }
            switch (requestCode) {
                //				case Constants.ACT_RULES_CREATE_SAMPLE_STEP02:
                //					Boolean bExit = data.getBooleanExtra(Constants.EXTRA_EXIT_FLAG, false);
                //					if (bExit) {
                //						Intent intent1 = new Intent();
                //						intent1.putExtra(Constants.EXTRA_EXIT_FLAG, bExit);
                //						this.setResult(RESULT_CANCELED, intent1);
                //						finish();
                //					}
                //					break;
            }
        }
    }

    @Override public void onListReload() {
        //        ComHandler.sendMessageDelayed(ComHandler.obtainMessage(MSG_COM_MEMBER_DEVICES), 10);
        // do something
    }

    @Override public void onLogout() {
        //        mCallback.onLogout();
    }
    @Override public void onCallAction(int iCallType, int iPosition) {

        iSelectPosition = iPosition;
        if ( iCallType == 0 ) {
            onBackPressed();
        } else if ( iCallType == 1 ) {
            Intent intent = new Intent(act, Invitation_List.class);
            util.callActivityForResultNoAnim(act, intent, Constants.ACT_INVITATION_LIST);
        } else if ( iCallType == 2 ) {
            sHTTP_status_code = "N";
            sHTTP_authorization_reply = "";
            sHTTP_nickname = util.null2string(alTotalList.get(iPosition).get(Constants.HTTP_nickname));
            sHTTP_homegrp_id = util.null2string(alTotalList.get(iPosition).get(Constants.HTTP_homegrp_id));
            sHTTP_target_email = util.null2string(alTotalList.get(iPosition).get(Constants.HTTP_target_email));
            sHTTP_homegrp_name = util.null2string(alTotalList.get(iPosition).get(Constants.HTTP_homegrp_name));
            sHTTP_authorization_question = util.null2string(alTotalList.get(iPosition).get(Constants.HTTP_authorization_question));
            customDialog.MsgAlert(act, Constants.MSG884, "[" + sHTTP_nickname + "] ");
        }
        //        intent = new Intent(act, Rules_Actions_Select.class);
        //        intent.putExtra(Constants.EXTRA_POSITION, util.null2int(alTotalList.get(iPosition).get(Constants.EXTRA_POSITION)));
        //        intent.putExtra(Constants.HTTP_item_name, util.null2string(alTotalList.get(iPosition).get(Constants.HTTP_item_name)));
        //        intent.putExtra(Constants.HTTP_pred_rule_id, util.null2string(alTotalList.get(iPosition).get(Constants.HTTP_pred_rule_id)));
        //        intent.putExtra(Constants.HTTP_pred_item_sequence, util.null2string(alTotalList.get(iPosition).get(Constants.HTTP_pred_item_sequence)));
        //        intent.putExtra(Constants.HTTP_item_sub_type_code, util.null2string(alTotalList.get(iPosition).get(Constants.HTTP_item_sub_type_code)));
        //        intent.putExtra(Constants.EXTRA_ACTIONS, alList_Actions);
        //        util.callActivityForResultNoAnim(act, intent, Constants.ACT_RULES_ACTIONS_SELECT);
    }
}