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

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

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.Home_Start;
import com.ntels.kneet.v3.view.dialog.CustomDialog;

import org.json.JSONObject;

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

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

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

    private static final int MSG_COM_P_HOMEGRP_MEMBERS_INVITATIONS = 1;
    private static final int MSG_COM_G_HOMEGRP_MEMBERS_INVITATIONS = 2;

    private Util         util         = new Util();
    private CustomDialog customDialog = new CustomDialog();
    private AppConfig               appConfig;
    private Main_Interface          mCallback;
    private Intent                  intent;
    private Activity                act;
    private Invitation_List_Adapter dataAdapter;
    private RecyclerView            rcvList;
    private SwipeRefreshLayout      swipeRefreshLayout;
    private GridLayoutManager       glmList;
    private LinearLayoutManager     llmList;
    private Toolbar                 toolbar;

    private ArrayList<HashMap<String, Object>> alTotalList                  = new ArrayList<HashMap<String, Object>>();
    private boolean                            loading                      = false;
    private boolean                            bListHeader                  = false;
    private boolean                            bListFooter                  = false;
    private boolean                            bListFooterAnd               = false;
    private boolean                            bReloadFinishFlag            = false;
    private int                                iType                        = 0;
    private int                                iListColumnsCnt              = 1;
    private int                                iSelectPosition              = 0;
    private String                             sHTTP_nickname               = "";
    private String                             sHTTP_homegrp_id             = "";
    private String                             sHTTP_status_code            = "";
    private String                             sHTTP_authorization_reply    = "";
    private String                             sHTTP_homegrp_name           = "";
    private String                             sHTTP_image_file_name        = "";
    private String                             sHTTP_authorization_question = "";
    private String                             sHTTP_error_count            = "";

    @Override protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        act = Invitation_List.this;
        appConfig = (AppConfig) act.getApplicationContext();
        customDialog.setOnMsgAlterToResultEvent(this);
        View viewToLoad = LayoutInflater.from(act).inflate(R.layout.invitation_list, 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_invitation_list_01));
    }

    private void displayListView() {

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

        swipeRefreshLayout = (SwipeRefreshLayout) 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;
                        //sSearchPlan = "U";
                        //sDateTime = sMaxDatetime;
                        ComHandler.sendMessageDelayed(ComHandler.obtainMessage(MSG_COM_G_HOMEGRP_MEMBERS_INVITATIONS), 10);
                    }
                } else {
                    swipeRefreshLayout.setRefreshing(false);
                }
            }
        });
        setRefresh(true);

        dataAdapter = new Invitation_List_Adapter(act, R.layout.row_invatation_list, R.layout.row_invatation_list, R.layout.row_invatation_list, alTotalList, this);
        rcvList = (RecyclerView) 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_line_01));
        //        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);
        ComHandler.sendMessageDelayed(ComHandler.obtainMessage(MSG_COM_G_HOMEGRP_MEMBERS_INVITATIONS), 10);
    }

    private void setRefresh(boolean bVal) {

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

    @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_P_HOMEGRP_MEMBERS_INVITATIONS:
                    send_P_homegrp_members_invitations();
                    break;
                case MSG_COM_G_HOMEGRP_MEMBERS_INVITATIONS:
                    send_G_homegrp_members_invitations();
                    break;

                default:
                    break;
            }
            return true;
        }
    }

    /**
     * <PRE>
     * 1. MethodName: send_G_homegrp_members_invitations
     * 2. ClassName :
     * 3. Comment   : [Send][GET]홈그룹 초대 목록(초대받은 홈그룹 목록을 호출)
     * 4. Developer : 최진오
     * 5. Created   : 2015. 10.
     * </PRE>
     */
    private void send_G_homegrp_members_invitations() {

        try {
            HttpSend httpSend;

            httpSend = new HttpSend(act, !swipeRefreshLayout.isRefreshing());
            //httpSend = new HttpSend(act);

            httpSend.setOnDataSendToReslutEvent(new OnDataSendToReslut() {
                @Override public void resultResponse(Response result) {

                    result_G_homegrp_members_invitations(result);
                }
            });
            httpSend.G_homegrp_members_invitations();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * <PRE>
     * 1. MethodName: result_G_homegrp_members_invitations
     * 2. ClassName :
     * 3. Comment   : [Result][GET]홈그룹 초대 목록(초대받은 홈그룹 목록을 호출)
     * 4. Developer : 최진오
     * 5. Created   : 2015. 10.
     * </PRE>
     */
    private void result_G_homegrp_members_invitations(Response rpResult) {

        try {
            if ( rpResult.getStatusCode() == 200 ) {
                alTotalList.clear();
                ArrayList<HashMap<String, Object>> alList = util.jsonToArrayListMap(rpResult.getContent());
                if ( alList.size() > 0 ) {
                    for ( int iRow = 0; iRow < alList.size(); iRow++ ) {
                        HashMap<String, Object> hmTemp = new HashMap<String, Object>();
                        hmTemp = alList.get(iRow);
                        alTotalList.add(hmTemp);
                    }
                } else {
                    onBackPressed();
                }
                util.getTextView(toolbar, R.id.tvToolbarTitle2).setText(alTotalList.size() + "");
                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);
        }
    }

    private void send_P_homegrp_members_invitations() {

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

                    result_P_homegrp_members_invitations(result);
                }
            });
            httpSend.P_homegrp_members_invitations(sHTTP_homegrp_id, sHTTP_status_code, sHTTP_authorization_reply);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    private void result_P_homegrp_members_invitations(Response rpResult) {

        try {
            if ( rpResult.getStatusCode() == 200 ) {
                sHTTP_error_count = "";
                if ( sHTTP_status_code.equals("Y") ) {
                    bReloadFinishFlag = true;
                    util.setPreferences(act, appConfig.getLogin_Id() + "Select_Homegrp_Id", sHTTP_homegrp_id);
                    customDialog.MsgAlert(act, Constants.MSG882, util.getString(act, R.string.layout_congratulations) + "\n[" + sHTTP_homegrp_name + "]\n");
                } else {
                    //                    util.setShowToast(act, "[" + sHTTP_homegrp_name + "]" + util.getString(act, R.string.MSG883), Toast.LENGTH_SHORT);
                    customDialog.MsgAlert(act, Constants.MSG883);
                }
            } 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));
                String sERR_COUNT = util.null2string(joResult.get(Constants.HTTP_error_count));

                if ( sERR_CODE.equals("401") ) {
                    customDialog.MsgAlert(act, Constants.MSG998, sERR_MSG);
                } else if ( sERR_CODE.equals("400-105") ) {
                    //재웅대리추가.... 홈허브있는상태? 초대?
                    customDialog.MsgAlert(act, Constants.MSG000, sERR_MSG);
                } else if ( sERR_CODE.equals("400-102") ) {
                    sHTTP_error_count = sERR_COUNT;
                    customDialog.MsgAlert(act, Constants.MSG999, 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;
            case Constants.MSG882:
                alTotalList.remove(iSelectPosition);

                if ( alTotalList.size() > 0 ) {
                    dataAdapter.notifyDataSetChanged();
                } else {
                    onBackPressed();
                }
                break;
            case Constants.MSG883:
                alTotalList.remove(iSelectPosition);

                if ( alTotalList.size() > 0 ) {
                    dataAdapter.notifyDataSetChanged();
                } else {
                    onBackPressed();
                }
                break;
            case Constants.MSG858:
                if ( iBtnResult == 1 ) {
                    Intent intent = new Intent(act, Invitation_Reply.class);
                    intent.putExtra(Constants.HTTP_homegrp_id, sHTTP_homegrp_id);
                    //                    intent.putExtra(Constants.HTTP_target_email, sHTTP_target_email);
                    intent.putExtra(Constants.HTTP_authorization_question, sHTTP_authorization_question);
                    intent.putExtra(Constants.HTTP_image_file_name, sHTTP_image_file_name);
                    util.callActivityForResultNoAnim(act, intent, Constants.ACT_INVITATION_REPLY);
                }
                break;
            case Constants.MSG884:
                if ( iBtnResult == 1 ) {
                    ComHandler.sendMessageDelayed(ComHandler.obtainMessage(MSG_COM_P_HOMEGRP_MEMBERS_INVITATIONS), 10);
                }
                break;
            case Constants.MSG999:
                if ( iBtnResult == 1 ) {
                    if ( util.str2int(sHTTP_error_count) < 3 ) {
                        Intent intent = new Intent(act, Invitation_Reply.class);
                        intent.putExtra(Constants.HTTP_homegrp_name, sHTTP_homegrp_name);
                        intent.putExtra(Constants.HTTP_authorization_question, sHTTP_authorization_question);
                        intent.putExtra(Constants.HTTP_image_file_name, sHTTP_image_file_name);
                        util.callActivityForResultNoAnim(act, intent, Constants.ACT_INVITATION_REPLY);
                    } else {
                        //재조회
                        ComHandler.sendMessageDelayed(ComHandler.obtainMessage(MSG_COM_G_HOMEGRP_MEMBERS_INVITATIONS), 10);
                    }
                }
                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);
        Boolean bReload_Flag = false;
        String sCALL_TYPE = "";
        if ( resultCode == RESULT_OK ) {
            switch (requestCode) {
                case Constants.ACT_INVITATION_REPLY:
                    intent = new Intent(act, Home_Start.class);
                    util.callActivityForResultNoAnim(act, intent, Constants.ACT_HOME_START);
                    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_INVITATION_REPLY:
                    bReload_Flag = data.getBooleanExtra(Constants.EXTRA_RELOAD_FLAG, false);
                    if ( bReload_Flag ) {
                        ComHandler.sendMessageDelayed(ComHandler.obtainMessage(MSG_COM_G_HOMEGRP_MEMBERS_INVITATIONS), 10);
                    }
                    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 ) {
            sHTTP_status_code = "Y";
            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_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));
            sHTTP_image_file_name = util.null2string(alTotalList.get(iPosition).get(Constants.HTTP_image_file_name));

            customDialog.MsgAlert(act, Constants.MSG858, "");
        } 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_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, "");
        }
    }
}
