package org.iri_research.renkan.repositories;

import java.io.Serializable;

import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.repository.query.MongoEntityInformation;
import org.springframework.data.mongodb.repository.support.MongoRepositoryFactory;
import org.springframework.data.mongodb.repository.support.SimpleMongoRepository;
import org.springframework.data.repository.core.RepositoryMetadata;

public class RenkanRepositoryFactory extends MongoRepositoryFactory {

	private MongoOperations mongoOperations;
	public RenkanRepositoryFactory(MongoOperations mongoOperations) {
		super(mongoOperations);
		this.mongoOperations = mongoOperations;
	}

	/*
	 * (non-Javadoc)
	 * @see org.springframework.data.repository.core.support.RepositoryFactorySupport#getTargetRepository(org.springframework.data.repository.core.RepositoryMetadata)
	 */
	@Override
	@SuppressWarnings({ "rawtypes", "unchecked" })
	protected Object getTargetRepository(RepositoryMetadata metadata) {
		
		Object res = super.getTargetRepository(metadata);
				
		if(SimpleMongoRepository.class.equals(res.getClass())) {
			MongoEntityInformation<?, Serializable> entityInformation = this.getEntityInformation(metadata.getDomainType());			
			return new RenkanRepository(entityInformation, this.mongoOperations);
		}
		else {
			return res;
		}

	}
	
	@Override
	protected Class<?> getRepositoryBaseClass(RepositoryMetadata metadata) {
		Class<?> res = super.getRepositoryBaseClass(metadata);
		if(SimpleMongoRepository.class.equals(res)) {
			return RenkanRepository.class;
		}
		else {
			return res;
		}
	}
	
}
