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

import java.util.Optional;
import java.util.stream.Stream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.apobates.forum.member.api.dao.MemberNamesProtectDao;
import com.apobates.forum.member.api.service.MemberNamesProtectService;
import com.apobates.forum.member.entity.MemberNamesProtect;

@Service
public class MemberNamesProtectServiceImpl implements MemberNamesProtectService{
	@Autowired
	private MemberNamesProtectDao memberNamesProtectDao;
	private final static Logger logger = LoggerFactory.getLogger(MemberNamesProtectServiceImpl.class);
	
	@Override
	public Stream<MemberNamesProtect> getAll() {
		return memberNamesProtectDao.findAll();
	}

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

	@Override
	public Optional<Boolean> editStatus(int id, boolean status) {
		Optional<MemberNamesProtect> data = get(id);
		if(!data.isPresent()){
			return Optional.empty();
		}
		MemberNamesProtect mnp = data.get();
		mnp.setStatus(status);
		
		return memberNamesProtectDao.edit(mnp);
	}

	@Override
	public Optional<MemberNamesProtect> create(String memberNames)throws IllegalStateException {
		MemberNamesProtect mnp = new MemberNamesProtect(memberNames);
		try {
			return build(mnp);
		}catch(Exception e) {
			throw new IllegalStateException(e.getMessage());
		}
	}

	@Override
	public Optional<MemberNamesProtect> create(String memberNames, boolean status)throws IllegalStateException {
		MemberNamesProtect mnp = new MemberNamesProtect(memberNames);
		mnp.setStatus(status);
		try {
			return build(mnp);
		}catch(Exception e) {
			throw new IllegalStateException(e.getMessage());
		}
	}

	@Override
	public Optional<Boolean> edit(int id, MemberNamesProtect updateEntity)throws IllegalStateException {
		Optional<MemberNamesProtect> data = get(id);
		if(!data.isPresent()){
			throw new IllegalStateException("保护帐号不存在");
		}
		MemberNamesProtect mnp = data.get();
		mnp.setStatus(updateEntity.isStatus());
		mnp.setMemberNames(updateEntity.getMemberNames());
		return memberNamesProtectDao.edit(mnp);
	}

	private Optional<MemberNamesProtect> build(MemberNamesProtect namesProtect) throws IllegalStateException {
		// 内置的不需要创建
		if (MemberNamesProtect.getNativeProtect().contains(namesProtect.getMemberNames())) {
			throw new IllegalStateException("内置保护的帐号不需要创建");
		}
		try {
			memberNamesProtectDao.save(namesProtect);
			return Optional.of(namesProtect);
		} catch (Exception e) {
			if (logger.isDebugEnabled()) {
				logger.debug("创建会员帐号保护失败", e);
			}
		}
		return Optional.empty();
	}
}
