package com.agilex.healthcare.schedulingmanager.datalayer.appointment;

import com.agilex.healthcare.schedulingmanager.datalayer.AbstractDao;
import com.agilex.healthcare.schedulingmanager.datalayer.SimpleEntityManager;
import com.agilex.healthcare.schedulingmanager.domain.SMAppointmentRequestInProcess;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.Query;
import java.util.List;

@Repository
public class AppointmentRequestInProcessDao extends AbstractDao{
    private static final String USER_ID = "userId";
	private static final String WHERE_ID = "from AppointmentRequestInProcessPo where id = :id";
    private static final String DELETE_BY_USER_ID = "delete from AppointmentRequestInProcessPo where userId = :userId";
	
	@Transactional(propagation = Propagation.REQUIRED)
    public SMAppointmentRequestInProcess save(SMAppointmentRequestInProcess SMAppointmentRequestInProcess) {
    	SimpleEntityManager<AppointmentRequestInProcessPo> simpleEntityManager = new SimpleEntityManager<AppointmentRequestInProcessPo>(entityManager);
        AppointmentRequestInProcessPo po = simpleEntityManager.save(new AppointmentRequestInProcessPo(SMAppointmentRequestInProcess));
        return po.create();
    }
	
    public SMAppointmentRequestInProcess get(String appointmentRequestId) {
        SimpleEntityManager<AppointmentRequestInProcessPo> simpleEntityManager = new SimpleEntityManager<AppointmentRequestInProcessPo>(WHERE_ID, entityManager);
        List<AppointmentRequestInProcessPo> results = simpleEntityManager.get(appointmentRequestId, AppointmentRequestInProcessPo.class);

        if (results.size() == 0)
            return null;

        return results.get(0).create();
    }
    
    @Transactional(propagation = Propagation.REQUIRED)
    public void deleteById(String appointmentRequestId) {
    	AppointmentRequestInProcessPo po = entityManager.find(AppointmentRequestInProcessPo.class, appointmentRequestId);
        entityManager.remove(po);
    }

    @Transactional(propagation = Propagation.REQUIRED)
    public void deleteByUserId(String userId) {
		Query query = this.entityManager.createQuery(DELETE_BY_USER_ID);
		query.setParameter(USER_ID, userId);
		query.executeUpdate();
    }
}
