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

import java.util.Iterator;

import com.agilex.healthcare.schedulingmanager.domain.CancelReason;
import com.agilex.healthcare.schedulingmanager.domain.CancelReasons;
import com.agilex.healthcare.schedulingmanager.mdws.MdwsResponseException;
import com.agilex.healthcare.schedulingmanager.mdws.generatedwsdl.schedulingservice.CancellationReasonTO;
import com.agilex.healthcare.schedulingmanager.mdws.generatedwsdl.schedulingservice.TaggedCancellationReasonsArray;

public class CancelReasonTranslator {

    public CancelReasons translate(TaggedCancellationReasonsArray arr) {
    	CancelReasons retValue = new CancelReasons();
    	if (arr == null)
    		throw new MdwsResponseException(MdwsResponseException.UserMessages.INVALID_DATA_RETURNED, "XXX was null");
    	if (arr.getFault() != null)
    		throw new MdwsResponseException(arr.getFault());
    	if (arr.getReasons() == null || arr.getReasons().getCancellationReasonTO() == null)
    		return retValue;

    	Iterator<CancellationReasonTO> itCancellationReasonTO = arr.getReasons().getCancellationReasonTO().iterator();
    	while (itCancellationReasonTO.hasNext()) {
    		CancellationReasonTO cancellationReasonTO = itCancellationReasonTO.next();
    		//Perform Error Checking
    		if (cancellationReasonTO.getFault() != null)
    			throw new MdwsResponseException(cancellationReasonTO.getFault());

    		CancelReason cancelReason = createCancelReason(cancellationReasonTO);
    		retValue.add(cancelReason);
    	}
    	
    	return retValue;
    }

    private CancelReason createCancelReason(CancellationReasonTO cancellationReasonTO) {
    	String id = cancellationReasonTO.getId();
        String name = cancellationReasonTO.getName();
		
        CancelReason cancelReason = new CancelReason();
        cancelReason.setNumber(id);
        cancelReason.setText(name);
        return cancelReason;
    }
}
