package eu.dnetlib.openaire.dsm.dao;

import java.sql.Date;
import java.util.Optional;

import javax.transaction.Transactional;

import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

import eu.dnetlib.openaire.dsm.domain.db.DatasourceDbEntry;

/**
 * Created by claudio on 12/04/2017.
 */
@Repository
@ConditionalOnProperty(value = "openaire.exporter.enable.dsm", havingValue = "true")
public interface DatasourceDbEntryRepository extends JpaRepository<DatasourceDbEntry, String>, JpaSpecificationExecutor<DatasourceDbEntry> {

	Optional<DatasourceDbEntry> findByNamespaceprefix(String namespaceprefix);

	@Query("select d.managed from #{#entityName} d where d.id = ?1")
	boolean isManaged(String id);

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

	@Modifying
	@Transactional
	@Query("update #{#entityName} d set d.officialname = ?2, d.englishname = ?3 where d.id = ?1")
	void setDatasourcename(String id, String officialname, String englishname);

	@Modifying
	@Transactional
	@Query("update #{#entityName} d set d.logourl = ?2 where d.id = ?1")
	void setLogoUrl(String dsId, String logourl);

	@Modifying
	@Transactional
	@Query("update #{#entityName} d set d.latitude = ?2, d.longitude = ?3 where d.id = ?1")
	void setCoordinates(String dsId, Double latitude, Double longitude);

	@Modifying
	@Transactional
	@Query("update #{#entityName} d set d.timezone = ?2 where d.id = ?1")
	void setTimezone(String dsId, String timezone);

	@Modifying
	@Transactional
	@Query("update #{#entityName} d set d.eoscDatasourceType = ?2 where d.id = ?1")
	void setEoscDatasourceType(String dsId, String type);

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

	@Query("select case when registrationdate <> null then true else false end as hasregistrationdate from #{#entityName} where id = ?1")
	Boolean hasRegistrationdate(String id);

	@Modifying
	@Transactional
	@Query("update #{#entityName} d set d.registrationdate = ?2 where d.id = ?1")
	void setRegistrationDate(String id, Date registrationdate);

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

}
