package com.reyun.service.impl;

import com.google.common.base.Function;
import com.google.common.collect.Lists;
import com.reyun.model.Account;
import com.reyun.model.IONotice;
import com.reyun.model.UserNoticeLog;
import com.reyun.repository.NoticeRepository;
import com.reyun.repository.UserNoticeLogRepository;
import com.reyun.service.NoticeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;

/**
 * Created by sunhao on 17/3/1.
 */
@Service
public class NoticeServiceImpl implements NoticeService {

    @Autowired
    private NoticeRepository noticeRepository;

    @Autowired
    private UserNoticeLogRepository userNoticeLogRepository;

    @Override
    public List<IONotice> listRecentDeployNotice(Long accountId) {

        List<IONotice> recentDeployNoticeList = noticeRepository.listRecentDeployNotice("<" + accountId + ">");

        if (!CollectionUtils.isEmpty(recentDeployNoticeList)) {

            List<Long> noticeIdList = Lists.transform(recentDeployNoticeList, new Function<IONotice, Long>() {
                @Override
                public Long apply(IONotice notice) {
                    return notice.getId();
                }
            });
            List<UserNoticeLog> userNoticeLogList = userNoticeLogRepository.listUserNoticeLog(accountId, noticeIdList);

            for (UserNoticeLog userNoticeLog : userNoticeLogList) {

                for (IONotice notice : recentDeployNoticeList) {

                    if (notice.getId().equals(userNoticeLog.getNoticeid())) {
                        notice.setIsRead(true);
                    }
                }
            }
        }

        return recentDeployNoticeList;
    }

    @Override
    public UserNoticeLog saveReadLog(UserNoticeLog userNoticeLog) {

        UserNoticeLog resultUserNoticeLog = userNoticeLogRepository.findUserNoticeLog(userNoticeLog.getNoticeid(), userNoticeLog.getAccountid());

        if (null == resultUserNoticeLog) {
            resultUserNoticeLog = userNoticeLogRepository.saveAndFlush(userNoticeLog);
        }

        return resultUserNoticeLog;
    }
}
