package com.apobates.forum.member.impl.service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import java.util.stream.Stream;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.apobates.forum.member.api.dao.MemberOnlineDao;
import com.apobates.forum.member.api.service.MemberOnlineService;
import com.apobates.forum.member.entity.MemberOnline;
import com.apobates.forum.utils.DateTimeUtils;

@Service
public class MemberOnlineServiceImpl implements MemberOnlineService{
	@Autowired
	private MemberOnlineDao memberOnlineDao;
	
	@Override
	public Optional<MemberOnline> get(long memberId) {
		return memberOnlineDao.findOne(memberId);
	}

	@Override
	public Stream<MemberOnline> get() {
		return memberOnlineDao.findAll();
	}

	@Override
	public Stream<MemberOnline> get(List<Long> memberIdList) {
		if(memberIdList == null || memberIdList.isEmpty()){
			return Stream.empty();
		}
		return memberOnlineDao.findAll(memberIdList);
	}

	@Override
	public long create(MemberOnline mo)throws IllegalStateException {
		Optional<MemberOnline> obj = get(mo.getMid());
		if(!obj.isPresent()){
			try{
				memberOnlineDao.save(mo);
				return mo.getMid();
			}catch(Exception e){
				throw new IllegalStateException(e.getMessage());
			}
		}else{
			MemberOnline data = obj.get();
			data.setAction(mo.getAction());
			data.setActiveDateTime(mo.getActiveDateTime());
			if(memberOnlineDao.edit(data).orElse(false)){
				return data.getMid();
			}
		}
		throw new IllegalStateException("创建或更新会员在线记录失败");
	}

	@Override
	public Stream<MemberOnline> get(LocalDateTime start, LocalDateTime finish) {
		return memberOnlineDao.findAll(start, finish);
	}

	@Override
	public Stream<MemberOnline> getForNow() {
		LocalDateTime finish = LocalDateTime.now();
		LocalDateTime start = DateTimeUtils.beforeMinuteForDate(finish, 30);
		return get(start, finish);
	}

	@Override
	public long count(LocalDateTime start, LocalDateTime finish) {
		return memberOnlineDao.countByDateTime(start, finish);
	}
}
