package com.reg.server.registration;

import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Optional;

@Service
public class RegistrationService {
	private final RegistrationMapper mapper;

	public RegistrationService(RegistrationMapper mapper) {
		this.mapper = mapper;
	}

	public List<Registration> list() {
		return mapper.findAll();
	}

	public Optional<Registration> get(Long id) {
		return mapper.findById(id);
	}

	public Registration create(Registration registration) {
		registration.setRegisterTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
		defaultStatus(registration);
		mapper.insert(registration);
		return registration;
	}

	public boolean update(Long id, Registration registration) {
		registration.setId(id);
		defaultStatus(registration);
		return mapper.update(registration) > 0;
	}

	public boolean delete(Long id) {
		return mapper.delete(id) > 0;
	}

	public List<Registration> search(Registration condition) {
		return mapper.findByCondition(condition);
	}

	private void defaultStatus(Registration registration) {
		if (!StringUtils.hasText(registration.getStatus())) {
			registration.setStatus("待登记");
		}
	}
}
