package com.ffii.core.support;

import java.io.Serializable;
import java.util.List;
import java.util.Optional;

import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import com.ffii.core.entity.IdEntity;

/** @author Alex */
public abstract class AbstractIdEntityService<T extends IdEntity<ID>, ID extends Serializable, R extends AbstractRepository<T, ID>>
		extends AbstractService {

	protected R repository;

	public AbstractIdEntityService(JdbcDao jdbcDao, R repository) {
		super(jdbcDao);
		this.repository = repository;
	}

	@Transactional(rollbackFor = Exception.class)
	public T save(T entity) {
		Assert.notNull(entity, "entity must not be null");
		return this.repository.save(entity);
	}

	@Transactional(rollbackFor = Exception.class)
	public T saveAndFlush(T entity) {
		Assert.notNull(entity, "entity must not be null");
		return this.repository.saveAndFlush(entity);
	}

	public List<T> listAll() {
		return this.repository.findAll();
	}

	public Optional<T> find(ID id) {
		Assert.notNull(id, "id must not be null");
		return this.repository.findById(id);
	}

	public boolean existsById(ID id) {
		Assert.notNull(id, "id must not be null");
		return this.repository.existsById(id);
	}

	public List<T> findAllByIds(List<ID> ids) {
		Assert.notNull(ids, "ids must not be null");
		return this.repository.findAllById(ids);
	}

	@Transactional(rollbackFor = Exception.class)
	public void delete(ID id) {
		Assert.notNull(id, "id must not be null");
		this.repository.deleteById(id);
	}

	@Transactional(rollbackFor = Exception.class)
	public void delete(T entity) {
		Assert.notNull(entity, "entity must not be null");
		this.repository.delete(entity);
	}
}
