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

package com.ntels.onecable.view.mainmore;

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.CustomActionBarActivity;
import com.ntels.onecable.view.Intro;
import com.ntels.onecable.view.dialog.CustomDialog;
import com.ntels.onecable.view.invitation.InvitationList;

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 :   MessageCenter
 * 2. FileName  :   MessageCenter.java
 * 3. Package   :   com.ntels.onecable.view.mainmore
 * 4. Date      :   2016-12-01
 * 5. Author    :   aaron
 * 6. Comment   :   Initialize
 * </pre>
 */
public class MessageCenter extends CustomActionBarActivity implements View.OnClickListener,
    CustomDialog.OnMsgAlterToResult,
        ListInterface {

  private AppConfig appConfig;
  private Util util = new Util();
  private CustomDialog customDialog = new CustomDialog();
  private Intent intent;
  private Activity act;
  private int type = 0;
  private ArrayList<HashMap<String, Object>> alTotalList = new ArrayList<HashMap<String, Object>>();
  private static final int MSG_COM_G_NOTICES_PERSONAL = 1;
  private MessageCenterAdapter dataAdapter;
  private SwipeRefreshLayout swipeRefreshLayout;
  private GridLayoutManager glmList;
  private LinearLayoutManager llmList;
  private boolean loading = false;
  private boolean isListHeader = false;
  private int listColumnsCnt = 1;

  private Toolbar toolbar;

  private String searchType = "";
  private String histId = "";
  private String maxHistId = "";
  private String minHistId = "";
  private boolean isMore = true;

  @Override
  protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    act = MessageCenter.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("");
  }

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

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

    RecyclerView recyclerView = (RecyclerView) act.findViewById(R.id.rcvList);
    recyclerView.setHasFixedSize(true);
    listColumnsCnt = 1;
    if (listColumnsCnt == 1) {
      llmList = new LinearLayoutManager(act);
      recyclerView.setLayoutManager(llmList);
    } else {
      glmList = new GridLayoutManager(act, listColumnsCnt, GridLayoutManager.VERTICAL, false);
      glmList.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 == MessageCenterAdapter.TYPE_HEADER) {
            return glmList.getSpanCount();
          } else {
            return dataAdapter.getItemViewType(position) == 1
                ? 1 : (valueCount % listColumnsCnt == 1 ? glmList.getSpanCount() : 1);
          }
        }
      });
      recyclerView.setLayoutManager(glmList);
    }
    recyclerView.addItemDecoration(new DividerItemDecoration(act, R.drawable.color_line_01,
        true, false));
    AlphaInAnimationAdapter alphaAdapter = new AlphaInAnimationAdapter(dataAdapter);
    alphaAdapter.setDuration(150);
    ScaleInAnimationAdapter scaleAdapter = new ScaleInAnimationAdapter(alphaAdapter);
    scaleAdapter.setDuration(150);
    recyclerView.setAdapter(scaleAdapter);

    recyclerView.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 (listColumnsCnt == 1) {
          totalItemCount = llmList.getItemCount();
          lastVisibleItem = llmList.findLastVisibleItemPosition();
        } else {
          totalItemCount = glmList.getItemCount();
          lastVisibleItem = glmList.findLastVisibleItemPosition();
        }
        if (lastVisibleItem >= totalItemCount - 1) {
          // 더보기 조회 중일때?
          if (!loading) {
            if (isMore) {
              loading = true;
              searchType = "D";
              histId = minHistId;

              HashMap<String, Object> hmTemp = new HashMap<String, Object>();
              hmTemp.put(Constants.KEY_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);
  }

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

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

  /**
   * Message badge clear.
   */
  private void setBadgeClear() {

    int badgeCnt = 0;
    util.setPreferences(getApplicationContext(), "badge_count", badgeCnt + "");
    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", badgeCnt);
    sendBroadcast(intent);
  }

  @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_G_NOTICES_PERSONAL:
          sendGetNoticesPersonal();
          break;
        default:
          break;
      }
      return true;
    }
  }

  /**
   * 알림 조회 요청.
   */
  private void sendGetNoticesPersonal() {

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

          resultGetNoticesPersonal(result);
        }
      });
      httpSend.G_notices_personal(histId, searchType);
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }

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

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

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

        //회원 번호
        String pushCount = util.null2string(joResult.get(Constants.KEY_PUSH_COUNT));
        String pushList = util.null2string(joResult.get(Constants.KEY_PUSH_LIST));

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

        if (searchType.equals("")) {
          alTotalList.clear();
          setBadgeClear();
          util.getTextView(toolbar, R.id.tvToolbarTitle2).setText(pushCount);
        }
        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.KEY_MORE_YN, "N");
            alTotalList.add(hmTemp);
          } else {
            HashMap<String, Object> hmTemp = new HashMap<String, Object>();
            hmTemp.put(Constants.KEY_MORE_YN, "N");
            alTotalList.set(alTotalList.size() - 1, hmTemp);
          }
          for (int row = 0; row < alList.size(); row++) {
            HashMap<String, Object> hmTemp;
            hmTemp = alList.get(row);
            String pushHistId = hmTemp.get(Constants.KEY_PUSH_NOTI_HIST_ID).toString();
            if (minHistId.equals("")) {
              minHistId = pushHistId;
            } else if (util.str2long(minHistId) > util.str2long(pushHistId)) {
              minHistId = pushHistId;
            }
            if (util.str2long(maxHistId) < util.str2long(pushHistId)) {
              maxHistId = pushHistId;
            }

            if (searchType.equals("U")) {
              alTotalList.add(row, 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.KEY_MORE_YN, "N");
            alTotalList.set(alTotalList.size() - 1, hmTemp);
          }
          if (searchType.equals("D")) {
            isMore = false;
          }
        }
        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, "");
    }
  }

  @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;
      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);
    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;
        default:
          break;
      }
    } else {
      if (appConfig.getGoErr()) {
        act.setResult(RESULT_CANCELED, new Intent());
        finish();
      }
    }
  }

  @Override
  public void onListReload() {
  }

  @Override
  public void onLogout() {
  }

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

    if (callType == 0) {
      onBackPressed();
    } else if (callType == 1) {
      Intent intent = new Intent(act, InvitationList.class);
      util.callActivityForResultNoAnim(act, intent, Constants.ACT_INVITATION_LIST);
    } else if (callType == 2) {
      String nickname = util.null2string(alTotalList.get(position).get(Constants.KEY_NICKNAME));
      customDialog.msgAlert(act, Constants.MSG884, "[" + nickname + "] ");
    }
  }
}