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

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

/**
 *
 * @author xiaofanku
 * @since 20200515
 */
@Service
public class RegisteInviteCodeServiceImpl implements RegisteInviteCodeService{
    @Autowired
    private RegisteInviteCodeDao registeInviteCodeDao;
    private final static Logger logger = LoggerFactory.getLogger(RegisteInviteCodeServiceImpl.class);
    
    @Override
    public Page<RegisteInviteCode> get(Pageable pageable) {
        return registeInviteCodeDao.findAll(pageable);
    }
    
    @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);
    }
    
    @Override
    public Optional<Boolean> remove(long id)throws IllegalArgumentException,IllegalStateException {
        RegisteInviteCode ric = get(id).orElseThrow(()->new IllegalArgumentException("注册邀请码不存在"));
        if (ric.isActive()) {
            throw new IllegalStateException("邀请码已经激活不可以删除");
        }
        ric.setStatus(false);
        return registeInviteCodeDao.edit(ric);
    }
    
    @Override
    public Optional<Boolean> activeCode(long id, long memberId, String memberNames) {
        return registeInviteCodeDao.active(id, memberId, memberNames);
    }
    
    @Override
    public long create(String leader, String code) {
        return create(new RegisteInviteCode(leader, code));
    }
    private long create(RegisteInviteCode inviteCode) {
        try {
            registeInviteCodeDao.save(inviteCode);
            if (inviteCode.getId() > 0) {
                return inviteCode.getId();
            }
        } catch (Exception e) {
            if(logger.isDebugEnabled()){
                logger.debug("注册邀请码创建失败", e);
            }
        }
        return 0L;
    }
}