package com.bizofficer.apiweb.testrunning;



import java.util.Iterator;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.TypedQuery;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.crossstore.ChangeSetPersister.NotFoundException;
import org.springframework.stereotype.Service;

import com.bizofficer.hibernate.entity.PgprepTestSummary;
import com.bizofficer.hibernate.repository.PgprepTestDetailsRepository;
import com.bizofficer.hibernate.repository.PgprepTestSummaryRepository;



@Service
public class TestRunDeleteService{
	
	private static final Logger logger = Logger.getLogger(TestRunDeleteService.class);
	
	@Autowired
	EntityManagerFactory entityManagerFactory;
	
	@Autowired
	PgprepTestDetailsRepository tdRepoObj;
	
	@Autowired
	PgprepTestSummaryRepository tsRepoObj;
	
	public Object doExecute(Object obj) throws NotFoundException{
		TestRunBean objBean = (TestRunBean) obj; 	
		TestRunResponseBean testSubmitResponseBeanObj = new TestRunResponseBean();
		
		try {
			testSubmitResponseBeanObj.setResponseTxt("failed");
			
			if(objBean.getOrganisationId()==null || objBean.getStudentId()==null) {
				return testSubmitResponseBeanObj;
			}
			
			logger.info("TestStopService Organisation Id: "+objBean.getOrganisationId() );
			logger.info("TestStopService Student Id: "+objBean.getStudentId() );
			
			EntityManager entityManager = entityManagerFactory.createEntityManager();
			entityManager.getTransaction().begin();
			
			TypedQuery<PgprepTestSummary> query = (TypedQuery<PgprepTestSummary>) entityManager.createQuery("from "+PgprepTestSummary.class.getName()+" where testStatus=0 and organisationId=:organisationId and studentId=:studentId order by id desc ", PgprepTestSummary.class);
			query.setParameter("organisationId", objBean.getOrganisationId()); 
			query.setParameter("studentId", objBean.getStudentId()); 
			query.setFirstResult(0);
			query.setMaxResults(1);
			List<?> resultListCat = query.getResultList();
			Iterator<?> iteratorCat=resultListCat.iterator();	
			if(iteratorCat.hasNext()){
				PgprepTestSummary myObj = (PgprepTestSummary)iteratorCat.next();
				PgprepTestSummary enquiryb = entityManager.find(PgprepTestSummary.class, myObj.getId());
				if(enquiryb != null){					
					entityManager.remove(enquiryb);
					entityManager.getTransaction().commit();
					testSubmitResponseBeanObj.setResponseTxt("OK");
		        }
			}
				
			entityManager.getTransaction().commit();
			entityManager.close();
				
		}catch(Exception e) {
			e.getStackTrace();
		}
		
		
		return testSubmitResponseBeanObj;
	}
	
	
	
	
}
