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

package com.ntels.onecable.admin.view.mainmore;

import com.ntels.onecable.admin.R;
import com.ntels.onecable.admin.common.AppConfig;
import com.ntels.onecable.admin.common.Constants;
import com.ntels.onecable.admin.common.c_interface.ListInterface;
import com.ntels.onecable.admin.common.c_interface.OnDataSendToReslut;
import com.ntels.onecable.admin.common.http.HttpSend;
import com.ntels.onecable.admin.common.http.Response;
import com.ntels.onecable.admin.common.util.Dlog;
import com.ntels.onecable.admin.common.util.Util;
import com.ntels.onecable.admin.common.util.recyclerview.DividerItemDecoration;
import com.ntels.onecable.admin.common.widget.CustomActivity;
import com.ntels.onecable.admin.view.HomeStart;
import com.ntels.onecable.admin.view.dialog.CustomDialog;
import com.ntels.onecable.admin.view.dialog.PushDialog;

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

    private static final int MSG_COM_P_NOTICES = 1;

    Handler mComHandler = new Handler(new IncomingHandlerCallBack());
    private Util mUtil = new Util();
    private CustomDialog mCustomDialog = new CustomDialog();
    private AppConfig mAppConfig;
    private Intent mIntent;
    private Activity mActivity;
    private NoticeAdapter mDataAdapter;
    private SwipeRefreshLayout mSwipeRefreshLayout;
    private GridLayoutManager mGlmList;
    private LinearLayoutManager mLlmList;
    private Toolbar mToolbar;
    private ArrayList<HashMap<String, Object>> mTotalList = new ArrayList<>();
    private boolean mLoading = false;
    private boolean mIsListHeader = false;
    private int mType = 0;
    private int mListColumnsCnt = 1;
    private String mSearchType = "";
    private String mReadDatetime = "";
    private String mNoticeId = "";
    private String maxNoticeId = "";
    private String minNoticeId = "";
    private boolean mIsMore = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        mActivity = Notice.this;
        mAppConfig = (AppConfig) mActivity.getApplicationContext();
        mCustomDialog.setOnMsgAlterToResultEvent(this);
        View viewToLoad = LayoutInflater.from(mActivity).inflate(R.layout.notice, 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.GONE);
        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_notice_01));
    }

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

        mUtil.getView(mActivity, R.id.llBtn1).setOnClickListener(this);

        mSwipeRefreshLayout = (SwipeRefreshLayout) mActivity.findViewById(R.id.swiperefreshlayout);
        mSwipeRefreshLayout.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);
        mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {

                if (!mDataAdapter.getListCheck()) {
                    if (!mLoading) {
                        mLoading = true;
                        mSearchType = "";
                        mNoticeId = "";
                        mReadDatetime = mUtil.getPreferences(mActivity, Constants.KEY_NOTICE_READ_DATETIME);
                        mComHandler.sendMessageDelayed(mComHandler.obtainMessage(MSG_COM_P_NOTICES), Constants.HANDLER_DELAY_MILLIS);
                    }
                } else {
                    mSwipeRefreshLayout.setRefreshing(false);
                }
            }
        });
        setRefresh(true);
        mLoading = false;

        mDataAdapter = new NoticeAdapter(0, R.layout.row_notice_list, R.layout.row_footer_add,
                mTotalList);
        mDataAdapter.setListCheck(false);
        mDataAdapter.setHeaderCheck(false);
        mDataAdapter.setFooterCheck(true);

        RecyclerView recyclerView = (RecyclerView) mActivity.findViewById(R.id.rcvList);
        recyclerView.setHasFixedSize(true);
        mListColumnsCnt = 1;
        if (mListColumnsCnt == 1) {
            mLlmList = new LinearLayoutManager(mActivity);
            recyclerView.setLayoutManager(mLlmList);
        } else {
            mGlmList = new GridLayoutManager(mActivity, mListColumnsCnt, GridLayoutManager.VERTICAL, false);
            mGlmList.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
                @Override
                public int getSpanSize(int position) {

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

                    if (positionType == mDataAdapter.TYPE_HEADER) {
                        return mGlmList.getSpanCount();
                    } else {
                        return mDataAdapter.getItemViewType(position) == 1 ? 1
                                : (valueCount % mListColumnsCnt == 1 ? mGlmList.getSpanCount() : 1);
                    }
                }
            });
            recyclerView.setLayoutManager(mGlmList);
        }
        recyclerView.addItemDecoration(new DividerItemDecoration(mActivity, R.drawable.color_line_01, true, false));

        AlphaInAnimationAdapter alphaAdapter = new AlphaInAnimationAdapter(mDataAdapter);
        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 (mListColumnsCnt == 1) {
                    totalItemCount = mLlmList.getItemCount();
                    lastVisibleItem = mLlmList.findLastVisibleItemPosition();
                } else {
                    totalItemCount = mGlmList.getItemCount();
                    lastVisibleItem = mGlmList.findLastVisibleItemPosition();
                }
                if (lastVisibleItem >= totalItemCount - 1) {
                    // 더보기 조회 중일때?
                    if (!mLoading) {
                        if (mIsMore) {
                            mLoading = true;
                            mSearchType = "D";
                            mNoticeId = minNoticeId;

                            HashMap<String, Object> hmTemp = new HashMap<String, Object>();
                            hmTemp.put(Constants.KEY_MORE_YN, "Y");
                            mTotalList.set(mTotalList.size() - 1, hmTemp);
                            mDataAdapter.notifyDataSetChanged();

                            mComHandler.sendMessageDelayed(mComHandler.obtainMessage(MSG_COM_P_NOTICES), Constants.HANDLER_DELAY_MILLIS);
                        }
                    }
                }
            }
        });

        mLoading = true;
        mSearchType = "";
        mNoticeId = "";
        mReadDatetime = mUtil.getPreferences(mActivity, Constants.KEY_NOTICE_READ_DATETIME);
        mComHandler.sendMessageDelayed(mComHandler.obtainMessage(MSG_COM_P_NOTICES), Constants.HANDLER_DELAY_MILLIS);
    }

    /**
     * mSwipeRefreshLayout enable/disable.
     *
     * @param isEnable true or false
     */
    private void setRefresh(boolean isEnable) {

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

    @Override
    public void onClick(View view) {

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

    /**
     * 공지사항 조회(공지사항 목록을 조회한다) 요청.
     */
    private void sendPostNotices() {

        try {
            HttpSend httpSend;

            if (mSearchType.equals("D")) {
                httpSend = new HttpSend(mActivity, false);
            } else {
                httpSend = new HttpSend(mActivity, !mSwipeRefreshLayout.isRefreshing());
            }

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

                    resultPostNotices(result);
                }
            });
            mUtil.setPreferences(mActivity, Constants.KEY_NOTICE_READ_DATETIME, mUtil.LocaltoUTC2(mUtil.getRealTime1()));
            httpSend.postNotices(mNoticeId, mSearchType, mReadDatetime);
//            httpSend.postNotices(mNoticeId, mSearchType, "");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

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

        try {
            if (response.getStatusCode() == 200) {
                JSONObject joResult = new JSONObject(response.getContent());
                Dlog.v(joResult.toString());

                if (mSearchType.equals("")) {
                    mTotalList.clear();
                }
                /*if (joResult.has(Constants.KEY_NOTICE_COUNT)) {
                    String noticeCount = mUtil.null2string(joResult.get(Constants.KEY_NOTICE_COUNT));
                    mUtil.getTextView(mToolbar, R.id.tvToolbarTitle2).setText(noticeCount);
                }*/
                ArrayList<HashMap<String, Object>> alList = new ArrayList<HashMap<String, Object>>();
                if (joResult.has(Constants.KEY_NOTICE_LIST)) {
                    String noticeList = mUtil.null2string(joResult.get(Constants.KEY_NOTICE_LIST));
                    alList = mUtil.jsonToArrayListMap(noticeList);
                }
                if (alList.size() > 0) {
                    mSwipeRefreshLayout.setVisibility(View.VISIBLE);
                    mUtil.getView(mActivity, R.id.llNodata1).setVisibility(View.GONE);
                    if (mTotalList.size() == 0) {
                        HashMap<String, Object> tempMap = new HashMap<>();
                        tempMap.put(Constants.KEY_MORE_YN, "N");
                        mTotalList.add(tempMap);
                    } else {
                        HashMap<String, Object> tempMap = new HashMap<>();
                        tempMap.put(Constants.KEY_MORE_YN, "N");
                        mTotalList.set(mTotalList.size() - 1, tempMap);
                    }
                    for (int row = 0; row < alList.size(); row++) {
                        HashMap<String, Object> hmTemp;
                        hmTemp = alList.get(row);
                        hmTemp.put(Constants.KEY_READ_DATETIME, mReadDatetime);
                        String noticeId = hmTemp.get(Constants.KEY_NOTICE_ID).toString();
                        if (minNoticeId.equals("")) {
                            minNoticeId = noticeId;
                        } else if (mUtil.str2long(minNoticeId) > mUtil.str2long(noticeId)) {
                            minNoticeId = noticeId;
                        }
                        if (mUtil.str2long(maxNoticeId) < mUtil.str2long(noticeId)) {
                            maxNoticeId = noticeId;
                        }

                        if (mSearchType.equals("U")) {
                            mTotalList.add(row, hmTemp);
                        } else {
                            mTotalList.add(mTotalList.size() - 1, hmTemp);
                        }
                    }
                } else {
                    if (mTotalList.size() == 0) {
                        mSwipeRefreshLayout.setVisibility(View.GONE);
                        mUtil.getView(mActivity, R.id.llNodata1).setVisibility(View.VISIBLE);
                    } else {
                        HashMap<String, Object> hmTemp = new HashMap<String, Object>();
                        hmTemp.put(Constants.KEY_MORE_YN, "N");
                        mTotalList.set(mTotalList.size() - 1, hmTemp);
                    }
                    if (mSearchType.equals("D")) {
                        mIsMore = false;
                    }
                }
                mLoading = false;
                mDataAdapter.notifyDataSetChanged();
                mSwipeRefreshLayout.setRefreshing(false);
            } else {
                JSONObject joResult = new JSONObject(response.getContent());
                Dlog.v(joResult.toString());
                String resultCode = mUtil.null2string(joResult.get(Constants.KEY_RESULT_CODE));
                String resultMsg = mUtil.null2string(joResult.get(Constants.KEY_RESULT_MSG));

                mCustomDialog.msgAlert(mActivity, Constants.MSG000, resultMsg);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            mCustomDialog.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(mType), Constants.HANDLER_DELAY_MILLIS);
                } else {
                    mActivity.onBackPressed();
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void onBackPressed() {

        mIntent = new Intent();
        mActivity.setResult(RESULT_CANCELED, mIntent);
        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_REPLY:
                    mIntent = new Intent(mActivity, HomeStart.class);
                    mUtil.callActivityForResultNoAnim(mActivity, mIntent, Constants.ACT_HOME_START);
                    break;
                case Constants.ACT_HOME_START:
                    mIntent = new Intent();
                    mActivity.setResult(RESULT_OK, mIntent);
                    finish();
                    break;
                default:
                    break;
            }
        } else {
            if (mAppConfig.getGoErr()) {
                mActivity.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();
        }
    }

    class IncomingHandlerCallBack implements Handler.Callback {

        @Override
        public boolean handleMessage(Message msg) {

            mType = msg.what;
            switch (msg.what) {
                case MSG_COM_P_NOTICES:
                    sendPostNotices();
                    break;

                default:
                    break;
            }
            return true;
        }
    }
}