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 Fung */
public abstract class AbstractIdEntityService<T extends IdEntity<ID>, ID extends Serializable, D extends AbstractDao<T, ID>>
		extends AbstractService {

	protected D dao;

	public AbstractIdEntityService(JdbcDao jdbcDao, D dao) {
		super(jdbcDao);
		this.dao = dao;
	}

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

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

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

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

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

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

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

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