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

import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.apobates.forum.member.api.dao.RegisteInviteCodeDao;
import com.apobates.forum.member.api.service.RegisteInviteCodeService;
import com.apobates.forum.member.entity.RegisteInviteCode;
import com.apobates.forum.utils.Commons;
import com.apobates.forum.utils.persistence.Page;
import com.apobates.forum.utils.persistence.Pageable;

@Service
public class RegisteInviteCodeServiceImpl implements RegisteInviteCodeService{
	@Autowired
	private RegisteInviteCodeDao registeInviteCodeDao;

	private long create(RegisteInviteCode inviteCode)throws IllegalStateException {
		try{
			registeInviteCodeDao.save(inviteCode);
			if(inviteCode.getId()>0){
				return inviteCode.getId();
			}
		}catch(Exception e){
			throw new IllegalStateException(e.getMessage());
		}
		throw new IllegalStateException("注册邀请码创建失败");
	}

	@Override
	public long create(String leader, String code) throws IllegalStateException{
		return create(new RegisteInviteCode(leader, code));
	}

	@Override
	public Page<RegisteInviteCode> get(Pageable pageable) {
		return registeInviteCodeDao.findAll(pageable);
	}

	@Override
	public Optional<Boolean> remove(long id)throws IllegalStateException {
		Optional<RegisteInviteCode> data = get(id);
		if(!data.isPresent()){
			throw new IllegalStateException("注册邀请码不存在");
		}
		RegisteInviteCode ric = data.get();
		if(ric.isActive()){
			throw new IllegalStateException("邀请码已经激活不可以删除");
		}
		ric.setStatus(false);
		
		return registeInviteCodeDao.edit(ric);
	}

	@Override
	public Optional<Boolean> activeCode(long id, long memberId, String memberNames) throws IllegalStateException{
		return registeInviteCodeDao.active(id, memberId, memberNames);
	}

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

	@Override
	public Optional<RegisteInviteCode> get(String code) {
		if(!Commons.isNotBlank(code)){
			return Optional.empty();
		}
		return registeInviteCodeDao.findOne(code);
	}
}
