package me.zhengjie.modules.dm.messageSendLog.service.impl;

import com.mongodb.WriteResult;
import com.mongodb.client.result.UpdateResult;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.dm.messageSendLog.domain.DmMessageSendLog;
import me.zhengjie.modules.dm.messageSendLog.service.DmMessageSendLogService;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.awt.print.Pageable;
import java.util.List;
import java.util.regex.Pattern;

@Service
@RequiredArgsConstructor
public class DmMessageSendLogServiceImpl implements DmMessageSendLogService {

    @Resource
    private MongoTemplate mongoTemplate;

    @Override
    public long getCount() {
        Query query = new Query();
        long count = mongoTemplate.count(query, DmMessageSendLog.class);
        return count;
    }

    @Override
    public DmMessageSendLog create(DmMessageSendLog resources) {
        resources.setIsRead(false);
        return  mongoTemplate.save(resources);
    }

    @Override
    public DmMessageSendLog findById(String id) {
        Query query=new Query(Criteria.where("_id").is(id));
        return mongoTemplate.findById(query,DmMessageSendLog.class);
    }

    @Override
    public List<DmMessageSendLog> findByUsername(String username){
        Pattern pattern = Pattern.compile("^.*" + username + ".*$");
        Query query=new Query(Criteria.where("usernames").regex(pattern));
        return mongoTemplate.find(query,DmMessageSendLog.class);
    }

    @Override
    public void updateById(String id){
        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(id));  //_id区分引号 "1"和1
        Update update = Update.update("is_read",true);
        mongoTemplate.upsert(query, update, DmMessageSendLog.class);//有则更新，没有则新增
    }

    @Override
    public List<DmMessageSendLog> queryAll() {
        return mongoTemplate.findAll(DmMessageSendLog.class);
    }

}
