package ai.pai.client.activity;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import com.android.common.executors.ThreadExecutor;
import com.android.common.utils.JSONParseUtils;
import com.android.common.utils.LogHelper;
import com.android.views.swiperefreshrecyclerview.DividerItemDecoration;
import com.android.views.swiperefreshrecyclerview.EndlessRecyclerOnScrollListener;
import com.android.views.swiperefreshrecyclerview.HeaderAndFooterRecyclerViewAdapter;

import org.json.JSONArray;
import org.json.JSONObject;

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

import ai.pai.client.R;
import ai.pai.client.adapter.MessageAdapter;
import ai.pai.client.beans.GroupPhotoItem;
import ai.pai.client.beans.MessageBean;
import ai.pai.client.db.Preferences;
import ai.pai.client.fragments.TabMessageFragment.MessageType;
import ai.pai.client.utils.HttpPostTask;
import ai.pai.client.utils.SystemUtils;
import ai.pai.client.utils.UrlContainer;
import ai.pai.client.views.MessageCleanPopup;

public class MessageActivity extends BaseActivity implements View.OnClickListener,SwipeRefreshLayout.OnRefreshListener,MessageAdapter.MessageActionListener {

    private RecyclerView recyclerView;
    private SwipeRefreshLayout swipeRefreshLayout;
    private MessageCleanPopup cleanPopup;
    private MessageAdapter refreshAdapter;
    private HeaderAndFooterRecyclerViewAdapter messageAdapter;
    private View loadMoreView;
    private View emptyView;

    private HttpPostTask fetchMessageTask;
    private HttpPostTask clearMessageTask;
    private HttpPostTask readMessageTask;

    private EndlessRecyclerOnScrollListener scrollListener;

    private ArrayList<MessageBean> messageList = new ArrayList<MessageBean>();

    private int left = Integer.MAX_VALUE;
    private static  final int num = 10;

    private String type ;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_message_push);
        SystemUtils.setImmerseLayout(this,findViewById(R.id.title_layout));
        type = getIntent().getStringExtra("type");
        TextView title = (TextView)findViewById(R.id.title_bar_middle_txt);
        if(MessageType.COMMENT.equals(type)){
            title.setText(R.string.message_comment);
        }else if(MessageType.SYSTEM.equals(type)){
            title.setText(R.string.message_push);
        }else {
            title.setText(R.string.message_thumbup);
        }
        findViewById(R.id.title_bar_back_layout).setOnClickListener(this);
        findViewById(R.id.title_bar_option_layout).setOnClickListener(this);
        emptyView = findViewById(R.id.layout_empty);
        swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout_msg);
        swipeRefreshLayout.setColorSchemeResources(R.color.colorPrimary);
        recyclerView = (RecyclerView) findViewById(R.id.recycler_view_msg);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.addItemDecoration(new DividerItemDecoration(this,DividerItemDecoration.VERTICAL_LIST));
        refreshAdapter = new MessageAdapter(this, messageList);
        messageAdapter = new HeaderAndFooterRecyclerViewAdapter(refreshAdapter);
        recyclerView.setAdapter(messageAdapter);
        refreshAdapter.addMessageDeleteListener(this);
        loadMoreView = LayoutInflater.from(this).inflate(R.layout.view_load_more, recyclerView, false);
        messageAdapter.addFooterView(loadMoreView);
        loadMoreView.setVisibility(View.GONE);
        swipeRefreshLayout.setOnRefreshListener(this);
        swipeRefreshLayout.setRefreshing(true);
        scrollListener = new EndlessRecyclerOnScrollListener() {
            @Override
            public void onLoadMore() {
                if(left > 0){
                    LogHelper.d(TAG,"message activity onLoadMore");
                    loadMoreView.setVisibility(View.VISIBLE);
                    doFetchMessageTask();
                }

            }
        };
        recyclerView.addOnScrollListener(scrollListener);
        doFetchMessageTask();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (clearMessageTask!=null && clearMessageTask.getStatus()== AsyncTask.Status.RUNNING){
            clearMessageTask.cancel(true);
        }
        if (fetchMessageTask!=null && fetchMessageTask.getStatus()== AsyncTask.Status.RUNNING){
            fetchMessageTask.cancel(true);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.title_bar_back_layout:
                finish();
                break;
            case R.id.title_bar_option_layout:
                if(cleanPopup==null){
                    cleanPopup = new MessageCleanPopup(this,this);
                }
                cleanPopup.showPopupWindow();
                break;
            case R.id.tv_pop_clean_msg:
                refreshAdapter.clearMessageList();
                doClearMessageTask(null);
                emptyView.setVisibility(refreshAdapter.getMessageList().size()==0 ? View.VISIBLE :View.GONE);
            case R.id.tv_pop_cancel:
                cleanPopup.dismiss();
                break;
            default:
                break;
        }
    }

    private synchronized void doFetchMessageTask(){
        if(fetchMessageTask!=null && fetchMessageTask.getStatus()== AsyncTask.Status.RUNNING){
            return;
        }
        if(refreshAdapter==null){
            return;
        }
        int page = refreshAdapter.getMessageList().size() /num +1;
        LogHelper.d(TAG,"message activity doFetchMessageTask  start with page "+page);
        HashMap<String,String> params = new HashMap<String,String>();
        String userId = Preferences.getInstance(this).getUserId();
        if(userId.length()==0){
            return;
        }
        params.put("user_id",userId);
        params.put("page",String.valueOf(page));
        params.put("num",String.valueOf(num));

        fetchMessageTask = new HttpPostTask(this,params) {
            ArrayList<MessageBean> messageItems = new ArrayList<MessageBean>();

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                scrollListener.setLoading(true);
            }

            @Override
            protected boolean parseResponse(Context context, String response) {
                try{
                    JSONObject json = new JSONObject(response);
                    int status = json.getInt("status");
                    if(status == 200){
                        LogHelper.d(TAG,"message activity doFetchMessageTask  parseResponse status 200");
                        JSONObject info = json.getJSONObject("data");
                        JSONArray msg_list = info.getJSONArray("messages");
                        if(msg_list!=null && msg_list.length()>0){
                            for(int count = 0; count<msg_list.length();count++){
                                JSONObject childMsg = msg_list.getJSONObject(count);
                                MessageBean childBean = new MessageBean();
                                childBean.createTime = JSONParseUtils.getJSONString(childMsg.getString("created_at"));
                                childBean.isRead = childMsg.getBoolean("read");
                                childBean.msgId = childMsg.getString("pk");
                                childBean.senderName = JSONParseUtils.getJSONString(childMsg.getString("from_nickname"));
                                childBean.senderAvatarUrl = JSONParseUtils.getJSONString(childMsg.getString("from_avatar"));
                                childBean.content = JSONParseUtils.getJSONString(childMsg.getString("msg_content"));
                                JSONObject photoObj = childMsg.getJSONObject("group_photo_info");
                                childBean.photoItem = GroupPhotoItem.parseFromJSON(photoObj);
                                messageItems.add(childBean);
                            }
                        }
                        left = info.getInt("left");
                        LogHelper.d(TAG,"message activity doFetchMessageTask  left="+left);
                        return true;
                    }
                }catch (Exception e){
                    LogHelper.e(TAG,"message activity doFetchMessageTask error happen "+e);
                }
                return false;
            }

            @Override
            protected void onPostFail(Context context) {
                super.onPostFail(context);
                scrollListener.setLoading(false);
                swipeRefreshLayout.setRefreshing(false);
                loadMoreView.setVisibility(View.GONE);
            }

            @Override
            protected void onPostSuccess(Context context) {
                super.onPostSuccess(context);
                scrollListener.setLoading(false);
                swipeRefreshLayout.setRefreshing(false);
                loadMoreView.setVisibility(View.GONE);
                if(refreshAdapter!=null&& messageItems !=null){
                    LogHelper.d(TAG, "message activity   has new message and update adapter :"+ messageItems.size());
                    refreshAdapter.addMessageList(messageItems);
                }
                emptyView.setVisibility(refreshAdapter.getMessageList().size()==0 ? View.VISIBLE :View.GONE);
                if(messageItems !=null){
                    doReadMessageTask();
                }
            }
        };
        fetchMessageTask.executeOnExecutor(ThreadExecutor.getInstance().getExecutor(), UrlContainer.MESSAGE_LIST_URL+"/"+type+"/list");
    }

    private synchronized void doClearMessageTask(String pk){
        if(clearMessageTask!=null && clearMessageTask.getStatus()== AsyncTask.Status.RUNNING){
            return;
        }
        LogHelper.d(TAG,"message activity doClearMessageTask  start ");
        HashMap<String,String> params = new HashMap<String,String>();
        String userId = Preferences.getInstance(this).getUserId();
        if(userId.length()==0){
            return;
        }
        params.put("user_id",userId);
        if(!TextUtils.isEmpty(pk)){
            params.put("pk",pk);
        }else{
            params.put("all","true");
        }
        clearMessageTask = new HttpPostTask(this,params) ;
        clearMessageTask.executeOnExecutor(ThreadExecutor.getInstance().getExecutor(), UrlContainer.CLEAR_MSG_URL+"/"+type+"/delete");
    }

    private synchronized void doReadMessageTask(){
        if(readMessageTask!=null && readMessageTask.getStatus()== AsyncTask.Status.RUNNING){
            return;
        }
        LogHelper.d(TAG,"message activity readMessageTask  start ");
        HashMap<String,String> params = new HashMap<String,String>();
        String userId = Preferences.getInstance(this).getUserId();
        if(userId.length()==0){
            return;
        }
        params.put("user_id",userId);
        params.put("all","true");
        readMessageTask = new HttpPostTask(this,params) ;
        readMessageTask.executeOnExecutor(ThreadExecutor.getInstance().getExecutor(), UrlContainer.CLEAR_MSG_URL+"/"+type+"/read");
    }

    @Override
    public void onRefresh() {
        LogHelper.d(TAG,"message activity onRefresh");
        if(refreshAdapter!=null){
            refreshAdapter.clearMessageList();
        }
        doFetchMessageTask();
    }

    @Override
    public void onMessageDeleted(String messageId) {
        doClearMessageTask(messageId);
        emptyView.setVisibility(refreshAdapter.getMessageList().size()==0 ? View.VISIBLE :View.GONE);
    }

}
