package com.example.leudaemialikeme.service;

import android.util.Log;

import com.example.leudaemialikeme.Dao.FriendDao;
import com.example.leudaemialikeme.Dao.MessageDao;
import com.example.leudaemialikeme.Model.Chat;
import com.example.leudaemialikeme.Model.Friend;
import com.example.leudaemialikeme.Model.Message;
import com.example.leudaemialikeme.Utils.TimeUtil;

import java.sql.Timestamp;
import java.util.ArrayList;

public class ChatService {
    private FriendDao friendDao;
    private MessageDao messageDao;

    public ChatService(){
        this.friendDao=new FriendDao();
        this.messageDao=new MessageDao();
    }

    //接收消息后进行发送者的判断，如果该消息不是本地同步的好友发送的，则先将消息保存，然后发送好友同步请求，然后再进行聊天列表的展示
    //这里需要先进行未读消息的朋友判断，改变isChat状态，然后再进行展示
    public ArrayList<Chat> findChatList(int ownerNetId){
        Log.d("记录","开始获取消息列表");
        ArrayList<Friend> isChatFriends = friendDao.findChatFriendList(ownerNetId);
        Log.d("chatservice","ischatfriends:"+isChatFriends.size());
        ArrayList<Chat> chats = new ArrayList<>();
        for (Friend friend : isChatFriends){
            Message message = messageDao.findLastMessage(friend.getNetId(),ownerNetId);
            Log.d("chatservice","lastmessage:"+message);
            Chat chat;
            if (message == null){
                chat = new Chat(friend.getNetId(),friend.getUsername(),"",1,"" );
            }else{
                String time= TimeUtil.timeToString(new Timestamp(message.getCreateTime()));
                /****/
                String lastMessage="";
                if (message.getMessageType()==1){
                    lastMessage=message.getContent();
                }else {
                    lastMessage="[图片]";
                }
                /****/
                chat = new Chat(friend.getNetId(),friend.getUsername(),lastMessage,message.getFlag(),time);
            }
            chats.add(chat);
        }

        return chats;
    }
}
