package com.rv.im;

import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.LinearLayout;

import com.ruiwenliu.wrapper.base.BaseBean;
import com.ruiwenliu.wrapper.base.BaseStatusActivity;
import com.ruiwenliu.wrapper.base.presenter.CommonPresenter;
import com.ruiwenliu.wrapper.weight.TitleView;
import com.ruiwenliu.wrapper.weight.refresh.SimpleRefreshLayout;
import com.ruiwenliu.wrapper.weight.refresh.SimpleRefreshView;
import com.rv.im.adapter.ChatConversationAdapter;
import com.rv.im.db.service.ChatConversationServiceImp;
import com.rv.im.db.service.ChatMessageServiceImp;
import com.rv.im.db.table.ChatConversation;
import com.rv.im.db.table.ChatMessage;
import com.rv.im.downloader.Downloader;
import com.rv.im.xmpp.ListenerManager;
import com.rv.im.xmpp.XmppConnectionManager;
import com.rv.im.xmpp.listener.AuthStateListener;
import com.rv.im.xmpp.listener.ChatMessageListener;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

public class ConversationListActivity extends BaseStatusActivity<CommonPresenter> implements SimpleRefreshLayout.OnSimpleRefreshListener, AuthStateListener, ChatMessageListener {

    private SimpleRefreshLayout refreshLayout;
    private RecyclerView recyclerView;
    private List<ChatConversation> conversations = new ArrayList<>();
    private ChatConversationAdapter adapter = null;

    @Override
    public void onShowResult(int requestType, BaseBean result) {

    }

    @Override
    protected int setLayout() {
        return R.layout.activity_conversation_lists;
    }

    @Override
    protected void initView(Bundle savedInstanceState, TitleView titleView, Intent intent) {

        ListenerManager.getInstance().addChatMessageListener(this);
        ListenerManager.getInstance().addAuthStateChangeListener(this);
        switch (XmppConnectionManager.mXMPPCurrentState) {
            case 0:
            case 1:
                titleView.setTitle("消息（连接中..）");
                break;
            case 2:
                titleView.setTitle("消息（在线）");
                break;
            default:
                titleView.setTitle("消息（离线）");
                break;
        }

//        titleView.setImageResource(R.id.iv_title_right, R.drawable.ic_app_add);
        titleView.setChildClickListener(R.id.tv_title_right, v -> {
            Intent in = new Intent(this, CustomerListActivity.class);
            startActivityForResult(in, 1);
        });
        titleView.setText(R.id.tv_title_right, "客服列表");
        refreshLayout = findViewById(R.id.refresh);
        recyclerView = findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayout.VERTICAL, false));
        refreshLayout.setHeaderView(new SimpleRefreshView(this));
        refreshLayout.setOnSimpleRefreshListener(this);
        adapter = new ChatConversationAdapter(conversations);
        adapter.setOnItemClickListener((adapter, view, position) -> {
            ChatConversation conversation = conversations.get(position);
            startActivityForResult(ChatActivity.getIntent(getApplicationContext(), conversation.getUserId(), conversation.getUserName()), 1);
        });
        recyclerView.setAdapter(adapter);

        File file = new File(getExternalCacheDir() + File.separator + ImSetting.getUserId() + File.separator + Environment.DIRECTORY_MUSIC);
        if (file != null && !file.exists()) {
            file.mkdirs();
        }

        Downloader.getInstance().init(file.getAbsolutePath());
    }


    @Override
    protected void loadData(Bundle savedInstanceState, Intent intent) {
        super.loadData(savedInstanceState, intent);
        initConversationList();
    }

    private void initConversationList() {
        List<ChatConversation> lists = ChatConversationServiceImp.getInstance(this).getAllConversation();
        if (lists != null && lists.size() > 0) {
            Iterator<ChatConversation> iterator = lists.iterator();
            while (iterator.hasNext()) {
                ChatConversation conversation = iterator.next();
                ChatMessage message = ChatMessageServiceImp.getInstance(getApplicationContext()).getLastMsg(conversation.getUserId());
                int unRead = ChatMessageServiceImp.getInstance(getApplicationContext()).getUnReadMsg(conversation.getUserId());
                conversation.setUnReadMessage(unRead);
                if (message != null) {
                    conversation.setLastMessageInfo(message);
                } else {
                    iterator.remove();
                }
            }
        }
        Collections.sort(lists, (o1, o2) -> {
            if (o1.getLastMessageTime() > o2.getLastMessageTime()) {
                return 1;
            } else if (o1.getLastMessageTime() == o2.getLastMessageTime()) {
                return 0;
            }
            return -1;
        });
        conversations.clear();
        conversations.addAll(lists);
        adapter.notifyDataSetChanged();
    }

    @Override
    public void onRefresh() {
        refreshLayout.onRefreshComplete();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        ListenerManager.getInstance().removeAuthStateChangeListener(this);
        ListenerManager.getInstance().removeChatMessageListener(this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1) { // 刷新UI
            initConversationList();
        }
    }

    @Override
    public void onAuthStateChange(int authState) {
        if (authState == AUTH_STATE_ING) {
            // 登录中
            if (titleView != null) {
                titleView.setTitle("消息（连接中..）");
            }
        } else if (authState == AUTH_STATE_SUCCESS) {
            // 在线
            if (titleView != null) {
                titleView.setTitle("消息（在线）");
            }
        } else if (authState == AUTH_STATE_NOT) {
            if (titleView != null) {
                titleView.setTitle("消息（离线）");
            }
        }
    }

    @Override
    public void onMessageSendStateChange(int messageState, String msgId) {

    }

    @Override
    public void onNewMessage(String fromUserId, ChatMessage message, boolean isGroupMsg) {
        initConversationList();
    }
}
