/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.csu.sdmx.web.validators;

import cz.csu.sdmx.web.forms.ValidatorForm;
import java.io.IOException;
import java.util.List;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
import org.springframework.web.multipart.MultipartFile;

/**
 *
 * @author themi
 */
@Component
public class ValidatorFormValidator implements Validator{

    @Override
    public boolean supports(Class<?> type) {
            return ValidatorForm.class.isAssignableFrom(type);
    }

    @Override
    public void validate(Object o, Errors errors) {
        ValidatorForm form = (ValidatorForm) o;
        MultipartFile SDMXDataFile = form.getSDMXDataFile();
        List<MultipartFile> dsdFiles = form.getDsdFiles();
        
        if(SDMXDataFile == null || SDMXDataFile.isEmpty()){
            errors.rejectValue("SDMXDataFile","dd", "SDMX data file required.");
        }
        
        try {
            if(dsdFiles != null && dsdFiles.size() > 0 && dsdFiles.get(0).getInputStream().available() < 1)
                errors.rejectValue("dsdFiles","dd", "DSD file required.");
        } catch (IOException ex) {
            errors.rejectValue("dsdFiles","dd", ex.getMessage());
        }
    }
}
