package com.ffii.core.support;

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

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

import com.ffii.core.entity.BaseEntity;
import com.ffii.core.exception.ConflictException;

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

	public AbstractBaseEntityService(JdbcDao jdbcDao, R repository) {
		super(jdbcDao, repository);
	}

	/** find and check versionId */
	public Optional<T> find(ID id, int version) {
		Assert.notNull(id, "id must not be null");
		return repository.findById(id)
				.map(entity -> {
					if (entity.getVersion() != version) throw new ConflictException("OPTIMISTIC_LOCK");
					return entity;
				});
	}

	@Transactional(rollbackFor = Exception.class)
	public void markDelete(ID id) {
		Assert.notNull(id, "id must not be null");
		find(id).ifPresent(t -> markDelete(t));
	}

	@Transactional(rollbackFor = Exception.class)
	public void markDelete(T entity) {
		Assert.notNull(entity, "entity must not be null");
		entity.setDeleted(Boolean.TRUE);
		save(entity);
	}
}
