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

package com.ntels.onecable.view.invitation;

import com.ntels.onecable.R;
import com.ntels.onecable.common.AppConfig;
import com.ntels.onecable.common.Constants;
import com.ntels.onecable.common.c_interface.ListInterface;
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.util.recyclerview.DividerItemDecoration;
import com.ntels.onecable.common.widget.CustomActivity;
import com.ntels.onecable.view.HomeStart;
import com.ntels.onecable.view.dialog.CustomDialog;

import org.json.JSONObject;

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

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

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

    private static final String TAG = InvitationList.class.getSimpleName();

    private static final int MSG_COM_P_HOMEGRP_MEMBERS_INVITATIONS = 1;
    private static final int MSG_COM_G_HOMEGRP_MEMBERS_INVITATIONS = 2;
    Handler mComHandler = new Handler(new IncomingHandlerCallBack());
    private Util mUtil = new Util();
    private CustomDialog customDialog = new CustomDialog();
    private AppConfig mAppConfig;
    private Intent intent;
    private Activity mActivity;
    private InvitationListAdapter dataAdapter;
    private SwipeRefreshLayout swipeRefreshLayout;
    private GridLayoutManager gridLayoutManager;
    private Toolbar mToolbar;
    private ArrayList<HashMap<String, Object>> alTotalList = new ArrayList<HashMap<String, Object>>();
    private boolean loading = false;
    private boolean isListHeader = false;
    private int type = 0;
    private int listColumnsCnt = 1;
    private int selectPosition = 0;
    private String homegrpId = "";
    private String statusCode = "";
    private String authorizationReply = "";
    private String homegrpName = "";
    private String imageFileName = "";
    private String authorizationQuestion = "";
    private String errorCount = "";
    //  private WebSocketService webSocketService;
    private boolean isBound = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        mActivity = InvitationList.this;
        mAppConfig = (AppConfig) mActivity.getApplicationContext();
        customDialog.setOnMsgAlterToResultEvent(this);

        setIsWebSocket(true);

        View viewToLoad = LayoutInflater.from(mActivity).inflate(R.layout.invitation_list, null);

        this.setContentView(viewToLoad);

        setToolbar();

        displayListView();
    }

    /**
     * 툴바 셋팅.
     */
    private void setToolbar() {

        mToolbar = (Toolbar) mActivity.findViewById(R.id.toolbar);
        mUtil.setKeyboardHide(mActivity, mToolbar);
        mUtil.getTextView(mToolbar, R.id.tvToolbarTitle1).setVisibility(View.VISIBLE);
        mUtil.getTextView(mToolbar, R.id.tvToolbarTitle2).setVisibility(View.VISIBLE);
        mUtil.getTextView(mToolbar, R.id.tvToolbarTitleDivider).setVisibility(View.GONE);
        mUtil.getTextView(mToolbar, R.id.tvToolbarTitle3).setVisibility(View.GONE);
        mUtil.getTextView(mToolbar, R.id.tvToolbarTitle4).setVisibility(View.GONE);
        mUtil.getTextView(mToolbar, R.id.btnToolbarClose).setVisibility(View.GONE);
        mUtil.getTextView(mToolbar, R.id.btnToolbarMore).setVisibility(View.GONE);

        mUtil.getTextView(mToolbar, R.id.tvToolbarTitle1).setText(mUtil.getString(mActivity, R.string.layout_invitation_list_01));
    }

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

        mUtil.getView(mActivity, 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;
                        mComHandler.sendMessageDelayed(mComHandler.obtainMessage(
                                MSG_COM_G_HOMEGRP_MEMBERS_INVITATIONS), 10);
                    }
                } else {
                    swipeRefreshLayout.setRefreshing(false);
                }
            }
        });
        setRefresh(true);

        dataAdapter = new InvitationListAdapter(mActivity, R.layout.row_invatation_list,
                R.layout.row_invatation_list, R.layout.row_invatation_list, alTotalList, this);
        RecyclerView recyclerView = (RecyclerView) findViewById(R.id.rcvList);

        recyclerView.setHasFixedSize(true);
        listColumnsCnt = 1;
        if (listColumnsCnt == 1) {
            LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mActivity);
            recyclerView.setLayoutManager(linearLayoutManager);
        } else {
            gridLayoutManager = new GridLayoutManager(mActivity, listColumnsCnt,
                    GridLayoutManager.VERTICAL, false);
            gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
                @Override
                public int getSpanSize(int position) {

                    int positionType = dataAdapter.getItemViewType(position);
                    int totalCount = dataAdapter.getItemCount();
                    int valueCount = dataAdapter.getItemCount();
                    if (isListHeader) {
                        valueCount = totalCount - 1;
                    }

                    if (positionType == InvitationListAdapter.TYPE_HEADER) {
                        return gridLayoutManager.getSpanCount();
                    } else {
                        return 1;
//                        return dataAdapter.getItemViewType(position) == 1
//                                ? 1 : (valueCount % listColumnsCnt == 1 ? gridLayoutManager.getSpanCount() : 1);
                    }
                }
            });
            recyclerView.setLayoutManager(gridLayoutManager);
        }
        recyclerView.addItemDecoration(new DividerItemDecoration(mActivity, R.drawable.color_line_01));
        AlphaInAnimationAdapter alphaAdapter = new AlphaInAnimationAdapter(dataAdapter);
        alphaAdapter.setDuration(150);
        ScaleInAnimationAdapter scaleAdapter = new ScaleInAnimationAdapter(alphaAdapter);
        scaleAdapter.setDuration(150);
        recyclerView.setAdapter(scaleAdapter);
        mComHandler.sendMessageDelayed(mComHandler.obtainMessage(
                MSG_COM_G_HOMEGRP_MEMBERS_INVITATIONS), 10);
    }

    /**
     * {@link #swipeRefreshLayout} enable/disable.
     *
     * @param isEnable true or false
     */
    private void setRefresh(boolean isEnable) {

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

    @Override
    public void onClick(View view) {

        switch (view.getId()) {
            case R.id.llBtn1:
                onBackPressed();
                break;
            default:
                break;
        }
    }

    /**
     * 홈그룹 초대 목록(초대받은 홈그룹 목록을 호출) 요청.
     */
    private void sendGetHomegrpMembersInvitations() {

        try {
            HttpSend httpSend;

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

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

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

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

        try {
            if (response.getStatusCode() == 200) {
                alTotalList.clear();
                ArrayList<HashMap<String, Object>> alList = mUtil.jsonToArrayListMap(response.getContent());
                if (alList.size() > 0) {
                    for (int row = 0; row < alList.size(); row++) {
                        HashMap<String, Object> tempMap;
                        tempMap = alList.get(row);
                        alTotalList.add(tempMap);
                    }
                } else {
                    onBackPressed();
                }
                mUtil.getTextView(mToolbar, R.id.tvToolbarTitle2).setText(String.valueOf(alTotalList.size()));
                loading = false;
                dataAdapter.notifyDataSetChanged();
                swipeRefreshLayout.setRefreshing(false);
            } else {
                JSONObject joResult = new JSONObject(response.getContent());
                Dlog.v(joResult.toString());
//                String errorCode = mUtil.null2string(joResult.get(Constants.KEY_ERR_CODE));
                String resultCode = mUtil.null2string(joResult.get(Constants.KEY_RESULT_CODE));
//                String errorMsg = mUtil.null2string(joResult.get(Constants.KEY_ERR_MSG));
                String resultMsg = mUtil.null2string(joResult.get(Constants.KEY_RESULT_MSG));

                if (resultCode.equals("401")) {
                    customDialog.msgAlert(mActivity, Constants.MSG998, resultMsg);
                } else if (resultCode.equals("401-106")) {
                    customDialog.msgAlert(mActivity, Constants.MSG997, resultMsg);
                } else {
                    customDialog.msgAlert(mActivity, Constants.MSG000, resultMsg);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            customDialog.msgAlert(mActivity, Constants.MSG807);
        }
    }

    /**
     * <pre>
     * 홈그룹 초대 알림(홈초대 알림 화면에서 승락/거절 처리를 한다) 요청.
     * (초대 수락 처리 후에 나머지 요청은 거절한다)
     * </pre>
     */
    private void sendPostHomegrpMembersInvitations() {

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

                    resultPostHomegrpMembersInvitations(result);
                }
            });
            httpSend.P_homegrp_members_invitations(homegrpId, statusCode, authorizationReply);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

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

        try {
            if (response.getStatusCode() == 200) {
                errorCount = "";
                if (statusCode.equals("Y")) {
                    mUtil.setPreferences(mActivity, mAppConfig.getLoginId() + "Select_Homegrp_Id", homegrpId);
                    customDialog.msgAlert(mActivity, Constants.MSG882, mUtil.getString(mActivity, R.string.layout_congratulations) + "\n[" +
                            homegrpName + "]\n");
                    getWebSocketService().webSocketConnect();
                } else {
                    customDialog.msgAlert(mActivity, Constants.MSG883);
                }
            } else {
                JSONObject joResult = new JSONObject(response.getContent());
                Dlog.v(joResult.toString());
//                String errorCode = mUtil.null2string(joResult.get(Constants.KEY_ERR_CODE));
                String resultCode = mUtil.null2string(joResult.get(Constants.KEY_RESULT_CODE));
//                String errorMsg = mUtil.null2string(joResult.get(Constants.KEY_ERR_MSG));
                String resultMsg = mUtil.null2string(joResult.get(Constants.KEY_RESULT_MSG));
                String errorCount = mUtil.null2string(joResult.get(Constants.KEY_ERROR_COUNT));

                if (resultCode.equals("401")) {
                    customDialog.msgAlert(mActivity, Constants.MSG998, resultMsg);
                } else if (resultCode.equals("400-105")) {
                    //재웅대리추가.... 홈허브있는상태? 초대?
                    customDialog.msgAlert(mActivity, Constants.MSG000, resultMsg);
                } else if (resultCode.equals("400-102")) {
                    this.errorCount = errorCount;
                    customDialog.msgAlert(mActivity, Constants.MSG999, resultMsg);
                } else if (resultCode.equals("401-106")) {
                    customDialog.msgAlert(mActivity, Constants.MSG997, resultMsg);
                } else {
                    customDialog.msgAlert(mActivity, Constants.MSG000, resultMsg);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            customDialog.msgAlert(mActivity, Constants.MSG807);
        }
    }

    @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(type), 10);
                } else {
                    mActivity.onBackPressed();
                }
                break;
            case Constants.MSG882:
                alTotalList.remove(selectPosition);

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

                if (alTotalList.size() > 0) {
                    dataAdapter.notifyDataSetChanged();
                } else {
                    onBackPressed();
                }
                break;
            case Constants.MSG858:
                if (btnResult == 1) {
                    Intent intent = new Intent(mActivity, InvitationReply.class);
                    intent.putExtra(Constants.KEY_HOMEGRP_ID, homegrpId);
                    intent.putExtra(Constants.KEY_AUTHORIZATION_QUESTION, authorizationQuestion);
                    intent.putExtra(Constants.KEY_IMAGE_FILE_NAME, imageFileName);
                    mUtil.callActivityForResultNoAnim(mActivity, intent, Constants.ACT_INVITATION_REPLY);
                }
                break;
            case Constants.MSG884:
                if (btnResult == 1) {
                    mComHandler.sendMessageDelayed(mComHandler.obtainMessage(
                            MSG_COM_P_HOMEGRP_MEMBERS_INVITATIONS), 10);
                }
                break;
            case Constants.MSG999:
                if (btnResult == 1) {
                    if (mUtil.str2int(errorCount) < 3) {
                        Intent intent = new Intent(mActivity, InvitationReply.class);
                        intent.putExtra(Constants.KEY_HOMEGRP_NAME, homegrpName);
                        intent.putExtra(Constants.KEY_AUTHORIZATION_QUESTION, authorizationQuestion);
                        intent.putExtra(Constants.KEY_IMAGE_FILE_NAME, imageFileName);
                        mUtil.callActivityForResultNoAnim(mActivity, intent, Constants.ACT_INVITATION_REPLY);
                    } else {
                        //재조회
                        mComHandler.sendMessageDelayed(mComHandler.obtainMessage(
                                MSG_COM_G_HOMEGRP_MEMBERS_INVITATIONS), 10);
                    }
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void onBackPressed() {

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

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

        super.onActivityResult(requestCode, resultCode, data);
        Boolean isReload = false;
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case Constants.ACT_INVITATION_REPLY:
                    getWebSocketService().webSocketConnect();
                    intent = new Intent(mActivity, HomeStart.class);
                    mUtil.callActivityForResultNoAnim(mActivity, intent, Constants.ACT_HOME_START);
                    break;
                case Constants.ACT_HOME_START:
                    intent = new Intent();
                    mActivity.setResult(RESULT_OK, intent);
                    finish();
                    break;
                default:
                    break;
            }
        } else {
            if (mAppConfig.getGoErr()) {
                mActivity.setResult(RESULT_CANCELED, new Intent());
                finish();
            }
            switch (requestCode) {
                case Constants.ACT_INVITATION_REPLY:
                    isReload = data.getBooleanExtra(Constants.EXTRA_RELOAD_FLAG, false);
                    if (isReload) {
                        mComHandler.sendMessageDelayed(mComHandler.obtainMessage(
                                MSG_COM_G_HOMEGRP_MEMBERS_INVITATIONS), 10);
                    }
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    public void onListReload() {
    }

    @Override
    public void onLogout() {
    }

    @Override
    public void onCallAction(int callType, int position) {

        selectPosition = position;
        if (callType == 0) {
            onBackPressed();
        } else if (callType == 1) {
            statusCode = "Y";
            authorizationReply = "";
            homegrpId = mUtil.null2string(alTotalList.get(position).get(Constants.KEY_HOMEGRP_ID));
            homegrpName = mUtil.null2string(alTotalList.get(position).get(Constants.KEY_HOMEGRP_NAME));
            authorizationQuestion = mUtil.null2string(
                    alTotalList.get(position).get(Constants.KEY_AUTHORIZATION_QUESTION));
            imageFileName = mUtil.null2string(
                    alTotalList.get(position).get(Constants.KEY_IMAGE_FILE_NAME));

            customDialog.msgAlert(mActivity, Constants.MSG858, "");
        } else if (callType == 2) {
            statusCode = "N";
            authorizationReply = "";
            homegrpId = mUtil.null2string(alTotalList.get(position).get(Constants.KEY_HOMEGRP_ID));
            homegrpName = mUtil.null2string(alTotalList.get(position).get(Constants.KEY_HOMEGRP_NAME));
            authorizationQuestion = mUtil.null2string(
                    alTotalList.get(position).get(Constants.KEY_AUTHORIZATION_QUESTION));
            customDialog.msgAlert(mActivity, Constants.MSG884, "");
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    class IncomingHandlerCallBack implements Handler.Callback {

        @Override
        public boolean handleMessage(Message msg) {

            type = msg.what;
            switch (msg.what) {
                case MSG_COM_P_HOMEGRP_MEMBERS_INVITATIONS:
                    sendPostHomegrpMembersInvitations();
                    break;
                case MSG_COM_G_HOMEGRP_MEMBERS_INVITATIONS:
                    sendGetHomegrpMembersInvitations();
                    break;

                default:
                    break;
            }
            return true;
        }
    }
}
