/**
 * Copyright © CENRA (2016)
 *
 * remi.clement@espaces-naturels.fr
 * 
 * This software is a multi-platform and portable application based on 
 * the scientifical toolbox to monitor wetlands. With this toolbox it’s 
 * possible to calculate indicators «RhoMéO» to monitor quality, 
 * fonctionalities and urban and agricultural pressures of wetlands. 
 * Indicators are calculated using naturalist data entered and/or imported,
 * and geographic data downloaded from a geographic server.
 * 
 * This software is governed by the CeCILL license under French law and
 * abiding by the rules of distribution of free software.  You can  use, 
 * modify and/ or redistribute the software under the terms of the CeCILL
 * license as circulated by CEA, CNRS and INRIA at the following URL
 * "http://www.cecill.info". 
 * 
 * As a counterpart to the access to the source code and  rights to copy,
 * modify and redistribute granted by the license, users are provided only
 * with a limited warranty  and the software's author,  the holder of the
 * economic rights,  and the successive licensors  have only  limited
 * liability. 
 * 
 * In this respect, the user's attention is drawn to the risks associated
 * with loading,  using,  modifying and/or developing or reproducing the
 * software by the user in light of its specific status of free software,
 * that may mean  that it is complicated to manipulate,  and  that  also
 * therefore means  that it is reserved for developers  and  experienced
 * professionals having in-depth computer knowledge. Users are therefore
 * encouraged to load and test the software's suitability as regards their
 * requirements in conditions enabling the security of their systems and/or 
 * data to be ensured and,  more generally, to use and operate it in the 
 * same conditions as regards security. 
 * 
 * The fact that you are presently reading this means that you have had
 * knowledge of the CeCILL license and that you accept its terms.
*/
package fr.cenra.rhomeo.core.validation;

import fr.cenra.rhomeo.api.InternationalResource;
import fr.cenra.rhomeo.api.Version;
import fr.cenra.rhomeo.api.annotations.RefersTo;
import fr.cenra.rhomeo.api.data.Reference;
import fr.cenra.rhomeo.core.RhomeoCore;
import fr.cenra.rhomeo.core.Session;
import fr.cenra.rhomeo.core.util.RelationResolver;
import java.util.Collections;
import java.util.Set;
import java.util.logging.Level;
import javafx.collections.MapChangeListener;
import javafx.collections.ObservableMap;
import javax.annotation.PostConstruct;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

/**
 * Ensure the property value is referring to an existing object. However, it
 * tests NEITHER nullity NOR blankness.
 *
 * @author Alexis Manin (Geomatys)
 */
@Component
@Scope("prototype")
public class ReferenceValidator implements ConstraintValidator<RefersTo, Object> {

    @Autowired
    private Session session;

    @Autowired
    private RelationResolver resolver;

    private Set expectedValues;

    private String propertyTitle;

    private RefersTo annot;

    private final MapChangeListener<Class, Version> changeListener;

    private ReferenceValidator() {
        changeListener = c -> {
            if (annot != null && annot.type() == c.getKey())
                initialize(this.annot);
        };
    }

    @PostConstruct
    private void init() {
        // Force refresh when edition step change.
        session.workflowStepProperty().addListener((obs) -> {
            if (annot != null)
                initialize(annot);
        });
    }

    @Override
    public void initialize(RefersTo annot) {
        this.annot = annot;
        try {
            final boolean bundleAvailable = InternationalResource.class.isAssignableFrom(annot.type());
            expectedValues = resolver.getPossibleValues(annot);
            // If possible, we try to get a readable title for referred property.
            propertyTitle = annot.property();
            if (bundleAvailable) {
                try {
                    propertyTitle = InternationalResource.getResourceString((Class) annot.type(), annot.property(), "label");
                } catch (Exception e) {
                    RhomeoCore.LOGGER.log(
                            Level.FINE, e,
                            () -> new StringBuilder("No bundle available for property ")
                            .append(annot.property())
                            .append(" of type ")
                            .append(annot.type()).toString()
                    );
                }
            }
        } catch (Exception ex) {
            RhomeoCore.LOGGER.log(Level.SEVERE, "Impossible to initialize validation capabilities for a reference !", ex);
            expectedValues = Collections.EMPTY_SET; // Cannot initialize comparison point : ALWAYS BAD.
        }

        // expected values could change if user modify the reference version to use.
        if (session.getDataContext() != null && Reference.class.isAssignableFrom(annot.type())) {
            final ObservableMap<Class<Reference>, Version> refs = session.getDataContext().getReferences();
            refs.removeListener(changeListener);
            refs.addListener(changeListener);
        }
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        if (value == null || ((value instanceof String) && ((String) value).trim().isEmpty())) {
            return true; // IGNORE NULLITY / BLANKNESS. Use @Blank and @Null annotations for this.

        } else if (!expectedValues.contains(value)) {
            final StringBuilder b = new StringBuilder();
            if (propertyTitle != null)
                b.append(propertyTitle).append(" : ");
            b.append("Aucune correspondance trouvée pour la valeur ").append(value);
            ConstraintValidatorContext.ConstraintViolationBuilder builder =
                    context.buildConstraintViolationWithTemplate(b.toString());
            builder.addConstraintViolation();
            context.disableDefaultConstraintViolation();

            return false;
        }

        return true;
    }
}
