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

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.ForumIpAddressRuleDao;
import com.apobates.forum.member.api.service.ForumIpAddressRuleService;
import com.apobates.forum.member.entity.ForumIpAddressRule;

@Service
public class ForumIpAddressRuleServiceImpl implements ForumIpAddressRuleService{
	@Autowired
	private ForumIpAddressRuleDao forumIpAddressRouleDao;

	@Override
	public Stream<ForumIpAddressRule> getAll() {
		return forumIpAddressRouleDao.findAll();
	}

	@Override
	public Optional<ForumIpAddressRule> create(String addrole)throws IllegalStateException {
		ForumIpAddressRule fia = new ForumIpAddressRule(addrole);
		try{
			forumIpAddressRouleDao.save(fia);
			return Optional.of(fia);
		}catch(Exception e){
			throw new IllegalStateException(e.getMessage());
		}
	}

	@Override
	public Optional<ForumIpAddressRule> create(String addrole, boolean status)throws IllegalStateException {
		ForumIpAddressRule fia = new ForumIpAddressRule(addrole);
		fia.setStatus(status);
		try{
			forumIpAddressRouleDao.save(fia);
			return Optional.of(fia);
		}catch(Exception e){
			throw new IllegalStateException(e.getMessage());
		}
	}

	@Override
	public Optional<ForumIpAddressRule> get(int id) {
		if(id>0){
			return forumIpAddressRouleDao.findOne(id);
		}
		return Optional.empty();
	}

	@Override
	public Optional<Boolean> editStatus(int id, final boolean status) {
		Optional<ForumIpAddressRule> opt = get(id);
		opt.ifPresent(role->{
			role.setStatus(status);
		});
		if(opt.isPresent()){
			return forumIpAddressRouleDao.edit(opt.get());
		}
		return Optional.empty();
	}

	@Override
	public Optional<Boolean> edit(int id, final ForumIpAddressRule updateEntity) {
		Optional<ForumIpAddressRule> opt = get(id);
		opt.ifPresent(role->{
			role.setRuleExpress(updateEntity.getRuleExpress());
			role.setStatus(updateEntity.isStatus());
		});
		if(opt.isPresent()){
			return forumIpAddressRouleDao.edit(opt.get());
		}
		return Optional.empty();
	}

	@Override
	public Stream<ForumIpAddressRule> getAll(boolean status) {
		return forumIpAddressRouleDao.findAll(status);
	}

	@Override
	public long count(boolean status) {
		return forumIpAddressRouleDao.count(status);
	}
}
