package de.jottyfan.camporganizer.module.registration;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import de.jottyfan.camporganizer.module.camplist.BookingBean;

/**
 *
 * @author jotty
 *
 */
@Service
public class RegistrationService {
	private final static Logger LOGGER = LogManager.getLogger(RegistrationService.class);

	@Autowired
	private RegistrationGateway gateway;

	@Autowired
	private KeycloakRepository keycloak;

	/**
	 * return true if the camp is not yet over
	 *
	 * @param fkCamp the camp ID
	 * @return true or false
	 */
	public Boolean campIsNotYetOver(Integer fkCamp) {
		return gateway.campIsNotYetOver(fkCamp);
	}

	/**
	 * get the camp
	 *
	 * @param fkCamp the ID of the camp
	 * @return the camp bean or null
	 */
	public CampBean getCamp(Integer fkCamp) {
		return gateway.getCamp(fkCamp);
	}

	/**
	 * register the person for a camp; if registerInKeycloak, do so also
	 *
	 * @param bean the bean
	 * @return true if successful, false otherwise
	 */
	public Boolean register(RegistrationBean bean, String currentUser) {
		if (currentUser != null) {
			bean.setRegisterInKeycloak(false); // already registered
			bean.setLogin(currentUser);
		}
		Boolean result = gateway.register(bean);
		if (result && bean.getRegisterInKeycloak()) {
			keycloak.register(bean.getForename(), bean.getSurname(), bean.getLogin(), bean.getPassword(), bean.getEmail());
		}
		return result;
	}

	/**
	 * get the booking bean
	 *
	 * @param id the id of the registration (t_person.pk)
	 * @return the booking bean or null
	 */
	public BookingBean getBooking(Integer id) {
		return gateway.getBooking(id);
	}

	/**
	 * remove the booking and all of its dependencies
	 *
	 * @param id the id of the booking (t_person.pk)
	 */
	public Boolean removeBooking(Integer id) {
		return gateway.removeBooking(id) > 0;
	}
}
