package com.agilex.healthcare.schedulingmanager.mdws.translator;

import java.util.Date;
import java.util.Iterator;

import org.joda.time.DateTime;
import org.joda.time.Days;

import com.agilex.healthcare.schedulingmanager.domain.SMConsult;
import com.agilex.healthcare.schedulingmanager.domain.SMConsults;
import com.agilex.healthcare.schedulingmanager.mdws.MdwsResponseException;
import com.agilex.healthcare.schedulingmanager.mdws.generatedwsdl.emrservice.ConsultTO;
import com.agilex.healthcare.schedulingmanager.mdws.generatedwsdl.emrservice.TaggedConsultArray;
import com.agilex.healthcare.schedulingmanager.mdws.generatedwsdl.emrservice.TaggedConsultArrays;
import com.agilex.healthcare.utility.DateHelper;

public class PatientConsultTranslator {

    //Patient Consult Translator
    public SMConsults translate(TaggedConsultArrays arr){
    	SMConsults retValue = new SMConsults();
    	if (arr == null)
    		throw new MdwsResponseException(MdwsResponseException.UserMessages.INVALID_DATA_RETURNED, "TaggedConsultArrays was null");
    	if (arr.getFault() != null)
    		throw new MdwsResponseException(arr.getFault());
    	if (arr.getArrays() == null || arr.getArrays().getTaggedConsultArray() == null)
    		return retValue;

    	Iterator<TaggedConsultArray> itTagged = arr.getArrays().getTaggedConsultArray().iterator();
    	while (itTagged.hasNext()) {
    		TaggedConsultArray tagged = itTagged.next();
    		//Perform Error Checking
    		if (tagged.getFault() != null)
    			throw new MdwsResponseException(tagged.getFault());

    		if (tagged.getConsults() == null || tagged.getConsults().getConsultTO() == null)
    			continue;

    		Iterator<ConsultTO> it = tagged.getConsults().getConsultTO().iterator();
    		while (it.hasNext()) {
    			ConsultTO consultTO = it.next();
    			//Perform Error Checking
    			if (consultTO.getFault() != null)
    				throw new MdwsResponseException(consultTO.getFault());

    			SMConsult smConsult = createSMConsult(consultTO);
    			retValue.add(smConsult);
    		}
    	}

    	return retValue;
    }

    private SMConsult createSMConsult(ConsultTO consultTO) {
        String id = consultTO.getId();
        String timestamp = consultTO.getTimestamp();
        String status = consultTO.getStatus();
        String text = consultTO.getText();
        String title = consultTO.getTitle();
		
        SMConsult smConsult = new SMConsult();
        smConsult.setConsultIen(id);
        if(timestamp != null) {
            Date requestDate = DateHelper.parseVistaDateTime(timestamp);
            DateTime today = new DateTime();
            int daysOnList = Days.daysBetween(new DateTime(requestDate), today).getDays();
            
            smConsult.setRequestDate(requestDate);
            smConsult.setDaysOnList(Integer.toString(daysOnList));
        }
        smConsult.setStatus(status);
        smConsult.setText(text);
        smConsult.setServiceName(title);
        return smConsult;
    }
}
