package objective.taskboard.project.config;

import objective.taskboard.cluster.base.BaseClusterService;
import objective.taskboard.domain.ProjectFilterConfiguration;
import objective.taskboard.jira.ProjectService;

import java.time.LocalDate;

import static org.apache.commons.lang3.StringUtils.isEmpty;

public class ProjectValidator {
    private ProjectValidator() { }

    private static final String PROJECT = "Project \"";

    public static void validateNonDuplicated(final ProjectFilterConfiguration project, final ProjectService projectService) {
        if (projectService.getTaskboardProject(project.getProjectKey()).isPresent())
            throw new ProjectValidationException("Project key \""+ project.getProjectKey() +"\" already exists.");
    }

    public static void validateDefinedDurationProject(final ProjectFilterConfiguration project, final BaseClusterService baseClusterService) {
        validateNonNull(project.getStartDate().orElse(null), "start date");
        validateNonNull(project.getBaseClusterId().orElse(null), "base cluster");

        project.getBaseClusterId().ifPresent(baseClusterService::validateExistance);
    }

    public static void validateNonEmpty(String value, String field) {
        if (isEmpty(value))
            throw new ProjectValidationException(PROJECT+ field +"\" cannot be empty.");
    }

    public static void validateNonNull(Object value, String field) {
        if (value == null)
            throw new ProjectValidationException(PROJECT+ field +"\" cannot be null.");
    }

    public static void validateStartIsBeforeEnd(LocalDate startDate, LocalDate deliveryDate, String startField, String endField) {
        if (startDate != null && deliveryDate != null && startDate.isAfter(deliveryDate))
            throw new ProjectValidationException("'"+startField+"' should be before or equal to '"+endField+"'");
    }

    public static class ProjectValidationException extends IllegalArgumentException {

        private static final long serialVersionUID = 1L;

        public ProjectValidationException(String message) {
            super(message);
        }

    }

}
