package eu.dnetlib.openaire.dsm.dao;

import java.util.List;
import javax.transaction.Transactional;

import eu.dnetlib.openaire.dsm.domain.db.ApiDbEntry;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

/**
 * Created by claudio on 15/06/2017.
 */
@Repository
@ConditionalOnProperty(value = "openaire.exporter.enable.dsm", havingValue = "true")
public interface ApiDbEntryRepository extends JpaRepository<ApiDbEntry, String> {

	@Query("select a from #{#entityName} a where a.datasource = ?1")
	List<ApiDbEntry> findByDatasource(String dsId);

	@Modifying
	@Transactional
	@Query("update #{#entityName} a set a.baseurl = ?2 where a.id = ?1")
	void setBaseurl(String id, String baseurl);

	@Modifying
	@Transactional
	@Query("update #{#entityName} a set a.compatibility = ?2 where a.id = ?1")
	void updateCompatibility(String apiId, String compatibility);

	@Modifying
	@Transactional
	@Query("update #{#entityName} a set a.compatibilityOverride = ?2 where a.id = ?1")
	void updateCompatibilityOverride(String apiId, String compatibility);

	@Modifying
	@Transactional
	@Query(value = "update dsm_apiparams ap set value = ?2 where ap.param = 'set' and ap.api = ?1", nativeQuery = true)
	void updateOaiSet(String apiId, String oaiSet);

	@Modifying
	@Transactional
	@Query(value = "insert into dsm_apiparams(api, param, value, _dnet_resource_identifier_) values(?1, ?2, ?3, ?1||'@@'||?2)", nativeQuery = true)
	void addApiParam(String apiId, String param, String value);

	@Modifying
	@Transactional
	@Query("update #{#entityName} d set d.removable = ?2 where d.datasource = ?1")
	void setRemovable(String id, boolean removable);

}
