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

import java.time.LocalDateTime;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.TreeMap;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.apobates.forum.member.api.dao.MemberActiveRecordsDao;
import com.apobates.forum.member.api.service.MemberActiveRecordsService;
import com.apobates.forum.member.entity.MemberActiveRecords;
import com.apobates.forum.utils.persistence.Page;
import com.apobates.forum.utils.persistence.Pageable;

@Service
public class MemberActiveRecordsServiceImpl implements MemberActiveRecordsService{
	@Autowired
	private MemberActiveRecordsDao memberActiveRecordsDao;

	@Override
	public Optional<MemberActiveRecords> get(long id) {
		return memberActiveRecordsDao.findOne(id);
	}

	@Override
	public Stream<MemberActiveRecords> getByMember(long memberId, String memberNames, int showSize) {
		return memberActiveRecordsDao.findAllByMember(memberId, memberNames, showSize);
	}

	@Override
	public long create(MemberActiveRecords entity)throws IllegalStateException {
		try{
			memberActiveRecordsDao.save(entity);
			return entity.getId();
		}catch(Exception e){
			throw new IllegalStateException(e.getMessage());
		}
	}

	@Override
	public Page<MemberActiveRecords> getByMember(long memberId, Pageable pageable) {
		return memberActiveRecordsDao.findAllByMember(memberId, pageable);
	}

	@Override
	public Page<MemberActiveRecords> getAll(Pageable pageable) {
		return memberActiveRecordsDao.findAll(pageable);
	}
	
	@Override
	public Optional<MemberActiveRecords> getPreviousLoginRecord(long memberId, String memberNames) {
		List<MemberActiveRecords> rs = memberActiveRecordsDao.findAllLoginAction(memberId, memberNames, 2).sorted(Comparator.comparing(MemberActiveRecords::getActiveDateTime).reversed()).collect(Collectors.toList());
		try {
			return Optional.ofNullable(rs.get(1));
		} catch (IndexOutOfBoundsException e) {
			return Optional.empty();
		}
	}
	
	@Override
	public Map<String, Long> statsDevice() {
		return memberActiveRecordsDao.groupForDevice();
	}

	@Override
	public Map<String, Long> statsIsp() {
		return memberActiveRecordsDao.groupForISP();
	}

	@Override
	public Map<String, Long> statsProvince() {
		return memberActiveRecordsDao.groupForProvince();
	}

	@Override
	public TreeMap<String, Long> groupMemberForActivity(LocalDateTime start, LocalDateTime finish) {
		return memberActiveRecordsDao.groupMemberForActivity(start, finish);
	}
}
