package eu.eudat.models.validators;

import eu.eudat.data.dao.criteria.DataManagementPlanCriteria;
import eu.eudat.logic.services.operations.DatabaseRepository;
import eu.eudat.models.data.dmp.DataManagementPlanNewVersionModel;
import eu.eudat.models.validators.fluentvalidator.FluentValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;

import java.util.Arrays;
import java.util.List;
import java.util.UUID;

/**
 * Created by ikalyvas on 3/7/2018.
 */
@Component("dataManagementPlanNewVersionValidator")
public class DataManagementPlanNewVersionValidator extends FluentValidator<DataManagementPlanNewVersionModel> {

    private DatabaseRepository databaseRepository;

    @Autowired
    public DataManagementPlanNewVersionValidator(DatabaseRepository databaseRepository) {
        this.databaseRepository = databaseRepository;

        ruleFor(x -> {
            DataManagementPlanCriteria criteria = new DataManagementPlanCriteria();
            List<UUID> groupIds = Arrays.asList(x.getGroupId());
            criteria.setGroupIds(groupIds);
            return this.databaseRepository.getDmpDao().getWithCriteria(criteria).getSingleOrDefault().getVersion();
        }).compareAs(x -> x.getVersion(), ((leftItem, rightItem) -> leftItem > rightItem))
                .withName("version").withMessage("datamanagementplannewversion.version.notacceptable");

        ruleFor(x -> {
            DataManagementPlanCriteria criteria = new DataManagementPlanCriteria();
            List<UUID> groupIds = Arrays.asList(x.getGroupId());
            criteria.setGroupIds(groupIds);
            return this.databaseRepository.getDmpDao().getWithCriteria(criteria).getSingleOrDefault().getVersion() + 1;
        }).compareAs(x -> x.getVersion(), ((leftItem, rightItem) -> !leftItem.equals(rightItem)))
                .withName("version").withMessage("datamanagementplannewversion.version.notnext");
    }

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


    public static boolean supportsType(Class<?> aClass) {
        return DataManagementPlanNewVersionModel.class.equals(aClass);
    }

}
