package cz.csu.sdmx.soap.endpoints;

import cz.csu.sdmx.dao.LogicConditionsDao;
import cz.csu.sdmx.dao.ValidationResultsDao;
import cz.csu.sdmx.soap.SoapFile;
import cz.csu.sdmx.soap.ValidationRequest;
import cz.csu.sdmx.soap.ValidationResponse;
import cz.csu.sdmx.validation.SDMXValidator;
import cz.csu.sdmx.validation.model.ValidationResult;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ws.server.endpoint.annotation.Endpoint;
import org.springframework.ws.server.endpoint.annotation.PayloadRoot;
import org.springframework.ws.server.endpoint.annotation.RequestPayload;
import org.springframework.ws.server.endpoint.annotation.ResponsePayload;

@Endpoint
public class ValidatorEndpoint extends BaseEndpoint{
	
        @Autowired
        private ValidationResultsDao resultsDao;
        
        @Autowired
        private LogicConditionsDao conditionsDao;

	@PayloadRoot(namespace = NAMESPACE_URI, localPart = "validationRequest")
	@ResponsePayload
	public ValidationResponse validate(@RequestPayload ValidationRequest request) {
            SDMXValidator validator = new SDMXValidator(conditionsDao);
            
            //add SoapFiles to SDMXValidator
            List<SoapFile> dsds = request.getDsd();
            for(int i = 0; i < dsds.size(); i++){
                SoapFile dsd = dsds.get(i);
                String name = dsd.getName();
                //if filename is not supplied, create one
                if(dsd.getName() == null || dsd.getName().isEmpty()){
                    name = "SOAP-DSD-File" + i;
                }
                //create InputStream and add to validator
                InputStream dsdIs = new ByteArrayInputStream(dsd.getBytes());
                validator.addDsd(name, dsdIs);
            }
            
            ValidationResult result = validator.getValidationResult();
            //if no errors found during DSD validation
            if(!result.hasErrors()){
                SoapFile data = request.getData();
                InputStream dataIs = new ByteArrayInputStream(data.getBytes());
                String dataName;
                
                //if filename is not supplied, create one
                if(data.getName() == null || data.getName().isEmpty())
                    dataName = "SOAP-Data-File";
                else
                    dataName = data.getName();

                //validate
                validator.validate(dataName, dataIs);
            }
            
            //insert into DB
            resultsDao.insert(result);
            
            //create and return response
            ValidationResponse response = factory.createValidationResponse();
            response.setValidationResult(result);
            
            return response;
	}
}
