package com.tenlionsoft.baselib.core.db.daos;

import com.tenlionsoft.baselib.core.beans.MessageBean;

import java.util.List;

import androidx.room.Dao;
import androidx.room.Delete;
import androidx.room.Insert;
import androidx.room.OnConflictStrategy;
import androidx.room.Query;

/**
 * 作者: adam
 * 日期: 1/18/21 - 5:36 PM
 * 邮箱: itgaojian@163.com
 * 描述: tableName=message
 */
@Dao
public interface MessageDao {
    /**
     * 获取全部信息
     *
     * @return
     */
    @Query("SELECT * FROM db_msg")
    List<MessageBean> getAllMsg();

    /**
     * 根据ID获取消息
     *
     * @param id
     * @return
     */
    @Query("SELECT * FROM db_msg WHERE id =(:id) ")
    List<MessageBean> getMsgById(String id);

    /**
     * 根据信息来源查询消息
     *
     * @param from
     * @return
     */
    @Query("SELECT * FROM db_msg WHERE `from`=(:from)")
    List<MessageBean> getMsgByFrom(String from);

    /**
     * 根据发送给谁进行查询
     *
     * @param to
     * @return
     */
    @Query("SELECT * FROM db_msg WHERE `to` =(:to)")
    List<MessageBean> getMsgByTo(String to);


    /**
     * 根据哪里
     *
     * @param form
     * @param pageSize
     * @param page
     * @return
     */
    @Query("SELECT * FROM db_msg WHERE `from`=(:form) ORDER BY timestamp LIMIT (((:page)-1)*(:pageSize)),(:pageSize)")
    List<MessageBean> getMsgByPage(String form, int pageSize, int page);

    /**
     * 查询与单人的聊天记录
     */
    @Query("SELECT * FROM db_msg t1 WHERE t1.id IN (SELECT id FROM db_msg WHERE `from`=(:form) AND `to`=(:to) OR `from`=(:to) AND `to`=(:form) ORDER BY timestamp DESC LIMIT (((:page)-1)*(:pageSize)),(:pageSize)) ORDER by t1.timestamp ASC")
    List<MessageBean> getMsgByFromOrToPage(String form, String to, int pageSize, int page);

    /**
     * 清空与某个人的聊天记录
     */
    @Query("DELETE FROM db_msg WHERE `from`=(:from) AND `to`=(:to) OR `from`=(:to) AND `to`=(:from)")
    void delChatHistory(String from, String to);

    /**
     * 添加消息多个
     *
     * @param beans
     */
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    void insertAll(MessageBean... beans);

    /**
     * 批量添加
     */
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    void insertAll(List<MessageBean> beans);

    /**
     * 添加消息-单个
     *
     * @param bean
     */
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    void insertMsg(MessageBean bean);

    /**
     * 清除全部聊天记录
     */
    @Query("DELETE FROM db_msg")
    void delAllMsg();
}
