

package gov.va.med.cds.persistence.hibernate;



import java.util.List;

import gov.va.med.cds.clinicaldata.DomainEntryPoint;
import gov.va.med.cds.exception.ErrorCodeEnum;
import gov.va.med.cds.persistence.ReadException;
import gov.va.med.cds.template.generated.surveyscommon.Survey;
import gov.va.med.cds.template.generated.surveyscommon.SurveyResponse;

import org.dom4j.Element;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Example;


public class WriteableDMPSurveyPersistenceManager
    extends
        WriteableSurveyPersistenceManager
{

	private static final String SURVEY_TYPE_DMP = "DMP";
	private static final String SURVEY = "survey";
	
    /**
     * Handles hibernate HDRII create processing.
     * 
     * @param session - active hibernate session.
     * @param aObject - create request.
     */
	@Override
    protected String createData( Session session, Object aObject, DomainEntryPoint domainEntryPoint )
    {
		SurveyResponse surveyResponse  = (SurveyResponse)unmarshalElementToObject((Element)aObject, domainEntryPoint);

        validateAndRetrieveVendor( session, surveyResponse );
        validateAndRetrieveFacility( session, surveyResponse );
		retrieveOrStoreSurvey(session, surveyResponse);
		verifyStoringQuestionsAndAnswers( session, surveyResponse );
        return session.save( surveyResponse ).toString();
    }
    
    
    /**
     * RQ 279.8	
     * HDR shall only persist HTH survey data to the HDR DB when the survey status is �ACCEPTED� 
     * and the data contains an answer for every question for the corresponding survey version.
     * 
     * @param session
     * @param aSurveyResponse
     */
    private void verifyStoringQuestionsAndAnswers( Session session, SurveyResponse aSurveyResponse )
    {
        if ( ! aSurveyResponse.getResponseStatus().equalsIgnoreCase("ACCEPTED") )
        {
        	aSurveyResponse.setSurveyQuestionsAndAnswersWithScores(null);
        }
    }


	@SuppressWarnings("unchecked")
	protected void retrieveOrStoreSurvey(Session session, SurveyResponse response) {
		List<Survey> results = null;
		Survey survey = response.getSurvey();
		survey.setSurveyType(SURVEY_TYPE_DMP);
		
		Criteria criteria = session.createCriteria(SURVEY);
		criteria.add(Example.create(survey));
		try {
			results = criteria.list();
		} catch (org.hibernate.exception.GenericJDBCException e) {
			throw new ReadException(ErrorCodeEnum.HIBERNATE_READ_FAILURE, e,
					e.getMessage());
		}
	
		if (results.size() < 1) {
			session.save(SURVEY,survey);
		}
		else{
			response.setSurvey(results.get(0));
		}
		
	}
    
}
