package org.iri_research.renkan.forms;

import java.io.IOException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.joda.JodaModule;

@Component
public class SpaceFormValidator implements Validator {

    private Logger logger = LoggerFactory.getLogger(SpaceFormValidator.class);

    @Override
    public boolean supports(Class<?> clazz) {
        return SpaceForm.class.equals(clazz);
    }

    @Override
    public void validate(Object target, Errors errors) {
        SpaceForm space = (SpaceForm) target;

        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "title",
                "renkan.error.title.empty");

        if (space.getBinConfig() != null && space.getBinConfig().length() > 0) {
            boolean valid = false;
            ObjectMapper mapper = new ObjectMapper();
            mapper.registerModule(new JodaModule());
            
            try {
                mapper.readTree(space.getBinConfig());
                valid = true;
            } catch (JsonProcessingException e) {
                logger.debug(
                        "SpaceValidator JsonProcessingException error validating bin config",
                        e);
            } catch (IOException e) {
                logger.debug(
                        "SpaceValidator IOException error validating bin config",
                        e);
            }
            if (!valid) {
                errors.rejectValue("binConfig", "renkan.error.bin_config.json");
            }
        }
    }

}
