package com.yaoyuan.jiscuss.service.impl;

import com.yaoyuan.jiscuss.entity.Notification;
import com.yaoyuan.jiscuss.repository.NotificationRepository;
import com.yaoyuan.jiscuss.service.INotificationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
public class NotificationServiceImpl implements INotificationService {

    @Autowired
    private NotificationRepository notificationRepository;

    @Transactional
    @Override
    public Notification create(Integer toUserId, Integer fromUserId, String type, String title,
                                String content, Integer relatedId, String relatedType) {
        // Do not notify yourself
        if (toUserId != null && toUserId.equals(fromUserId)) {
            return null;
        }
        Notification n = new Notification();
        n.setUserId(toUserId);
        n.setFromUserId(fromUserId);
        n.setType(type);
        n.setTitle(title);
        n.setContent(content);
        n.setRelatedId(relatedId);
        n.setRelatedType(relatedType);
        n.setIsRead(false);
        n.setCreateTime(new Date());
        return notificationRepository.save(n);
    }

    @Async
    @Override
    public void notifyReply(Integer toUserId, Integer fromUserId, Integer discussionId, String discussionTitle) {
        create(toUserId, fromUserId, "reply",
                "有人回复了你的帖子",
                "在话题《" + discussionTitle + "》中回复了你",
                discussionId, "discussion");
    }

    @Async
    @Override
    public void notifyLike(Integer toUserId, Integer fromUserId, Integer postId, Integer discussionId) {
        create(toUserId, fromUserId, "like",
                "有人赞了你的回复",
                null, postId, "post");
    }

    @Transactional(readOnly = true)
    @Override
    public long countUnread(Integer userId) {
        return notificationRepository.countByUserIdAndIsReadFalse(userId);
    }

    @Transactional(readOnly = true)
    @Override
    public Page<Notification> listByUser(Integer userId, int page, int size) {
        return notificationRepository.findByUserIdOrderByCreateTimeDesc(
                userId, PageRequest.of(page, size));
    }

    @Transactional
    @Override
    public void markAllRead(Integer userId) {
        notificationRepository.markAllReadByUserId(userId);
    }

    @Transactional
    @Override
    public void markOneRead(Integer notificationId, Integer userId) {
        notificationRepository.markReadById(notificationId, userId);
    }
}
