/*
 * 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.LogUtil;
import com.ntels.onecable.common.util.Util;
import com.ntels.onecable.common.util.recyclerview.DividerItemDecoration;
import com.ntels.onecable.common.websocket.WebSocketService;
import com.ntels.onecable.common.widget.CustomActionBarActivity;
import com.ntels.onecable.view.HomeStart;
import com.ntels.onecable.view.dialog.CustomDialog;

import org.json.JSONObject;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
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 CustomActionBarActivity 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;

  private Util util = new Util();
  private CustomDialog customDialog = new CustomDialog();
  private AppConfig appConfig;
  private Intent intent;
  private Activity act;
  private InvitationListAdapter dataAdapter;
  private SwipeRefreshLayout swipeRefreshLayout;
  private GridLayoutManager gridLayoutManager;
  private Toolbar toolbar;

  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);
    act = InvitationList.this;
    appConfig = (AppConfig) act.getApplicationContext();
    customDialog.setOnMsgAlterToResultEvent(this);

    Intent serviceIntent = new Intent(act, WebSocketService.class);
    act.bindService(serviceIntent, serviceConnection, Context.BIND_AUTO_CREATE);

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

    this.setContentView(viewToLoad);

    setToolbar();

    displayListView();
  }

  private ServiceConnection serviceConnection = new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
      LogUtil.i(TAG, "onServiceConnected!!");
      WebSocketService.WebSocketBinder binder = (WebSocketService.WebSocketBinder) service;
      webSocketService = binder.getService();
      isBound = true;
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {
      isBound = false;
    }
  };

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

  /**
   * UI display.
   */
  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;
            comHandler.sendMessageDelayed(comHandler.obtainMessage(
                MSG_COM_G_HOMEGRP_MEMBERS_INVITATIONS), 10);
          }
        } else {
          swipeRefreshLayout.setRefreshing(false);
        }
      }
    });
    setRefresh(true);

    dataAdapter = new InvitationListAdapter(act, 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(act);
      recyclerView.setLayoutManager(linearLayoutManager);
    } else {
      gridLayoutManager = new GridLayoutManager(act, 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 dataAdapter.getItemViewType(position) == 1
                ? 1 : (valueCount % listColumnsCnt == 1 ? gridLayoutManager.getSpanCount() : 1);
          }
        }
      });
      recyclerView.setLayoutManager(gridLayoutManager);
    }
    recyclerView.addItemDecoration(new DividerItemDecoration(act, R.drawable.color_line_01));
    AlphaInAnimationAdapter alphaAdapter = new AlphaInAnimationAdapter(dataAdapter);
    alphaAdapter.setDuration(150);
    ScaleInAnimationAdapter scaleAdapter = new ScaleInAnimationAdapter(alphaAdapter);
    scaleAdapter.setDuration(150);
    recyclerView.setAdapter(scaleAdapter);
    comHandler.sendMessageDelayed(comHandler.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;
    }
  }

  Handler comHandler = new Handler(new IncomingHandlerCallBack());

  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;
    }
  }

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

    try {
      HttpSend httpSend;

      httpSend = new HttpSend(act, !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 = util.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();
        }
        util.getTextView(toolbar, 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 = 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 {
          customDialog.msgAlert(act, Constants.MSG000, errorMsg);
        }
      }
    } catch (Exception ex) {
      ex.printStackTrace();
      customDialog.msgAlert(act, Constants.MSG807);
    }
  }

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

    try {
      HttpSend httpSend;
      httpSend = new HttpSend(act);
      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")) {
          util.setPreferences(act, appConfig.getLogin_Id() + "Select_Homegrp_Id", homegrpId);
          customDialog.msgAlert(act, Constants.MSG882,
              util.getString(act, R.string.layout_congratulations) + "\n[" + homegrpName + "]\n");
          webSocketService.webSocketConnect();
        } else {
          customDialog.msgAlert(act, Constants.MSG883);
        }
      } 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));
        String errorCount = util.null2string(joResult.get(Constants.KEY_ERROR_COUNT));

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

  @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);
        } else {
          act.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(act, InvitationReply.class);
          intent.putExtra(Constants.KEY_HOMEGRP_ID, homegrpId);
          intent.putExtra(Constants.KEY_AUTHORIZATION_QUESTION, authorizationQuestion);
          intent.putExtra(Constants.KEY_IMAGE_FILE_NAME, imageFileName);
          util.callActivityForResultNoAnim(act, intent, Constants.ACT_INVITATION_REPLY);
        }
        break;
      case Constants.MSG884:
        if (btnResult == 1) {
          comHandler.sendMessageDelayed(comHandler.obtainMessage(
              MSG_COM_P_HOMEGRP_MEMBERS_INVITATIONS), 10);
        }
        break;
      case Constants.MSG999:
        if (btnResult == 1) {
          if (util.str2int(errorCount) < 3) {
            Intent intent = new Intent(act, InvitationReply.class);
            intent.putExtra(Constants.KEY_HOMEGRP_NAME, homegrpName);
            intent.putExtra(Constants.KEY_AUTHORIZATION_QUESTION, authorizationQuestion);
            intent.putExtra(Constants.KEY_IMAGE_FILE_NAME, imageFileName);
            util.callActivityForResultNoAnim(act, intent, Constants.ACT_INVITATION_REPLY);
          } else {
            //재조회
            comHandler.sendMessageDelayed(comHandler.obtainMessage(
                MSG_COM_G_HOMEGRP_MEMBERS_INVITATIONS), 10);
          }
        }
        break;
      default:
        break;
    }
  }

  @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 isReload = false;
    if (resultCode == RESULT_OK) {
      switch (requestCode) {
        case Constants.ACT_INVITATION_REPLY:
          webSocketService.webSocketConnect();
          intent = new Intent(act, HomeStart.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;
        default:
          break;
      }
    } else {
      if (appConfig.getGoErr()) {
        act.setResult(RESULT_CANCELED, new Intent());
        finish();
      }
      switch (requestCode) {
        case Constants.ACT_INVITATION_REPLY:
          isReload = data.getBooleanExtra(Constants.EXTRA_RELOAD_FLAG, false);
          if (isReload) {
            comHandler.sendMessageDelayed(comHandler.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 = util.null2string(alTotalList.get(position).get(Constants.KEY_HOMEGRP_ID));
      homegrpName = util.null2string(alTotalList.get(position).get(Constants.KEY_HOMEGRP_NAME));
      authorizationQuestion = util.null2string(
          alTotalList.get(position).get(Constants.KEY_AUTHORIZATION_QUESTION));
      imageFileName = util.null2string(
          alTotalList.get(position).get(Constants.KEY_IMAGE_FILE_NAME));

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

  @Override
  protected void onDestroy() {
    super.onDestroy();
    if (isBound) {
      unbindService(serviceConnection);
      isBound = false;
    }
  }
}
