package de.schilling.workinghours.duration;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author David Schilling - davejs92@gmail.com
 */
@Service
public class DurationValidationServiceImpl implements DurationValidationService {

    private final DurationRepository durationRepository;

    @Autowired
    public DurationValidationServiceImpl(DurationRepository durationRepository) {
        this.durationRepository = durationRepository;
    }

    @Override
    public boolean validateNewDuration(Duration duration) {
        if(duration.getEndTime() != null && duration.getDuration() == 0) {
            return false;
        }
        if(duration.getStartTime() == null) {
            return false;
        }
        boolean foundInvalidCombination = false;
        List<Duration> durationList = durationRepository.findByUsernameOrderByStartTimeDesc(duration.getUsername());
        for (Duration currentDuration : durationList) {
            if (currentDuration.getEndTime() == null) {
                if (!isAfterFirstOrEqual(currentDuration.getStartTime(), duration.getEndTime()) &&
                        !currentDuration.getStartTime().isBefore(duration.getStartTime())) {
                    foundInvalidCombination = true;
                }
            } else {
                if (duration.getEndTime() == null) {
                    if (duration.getStartTime().isBefore(currentDuration.getEndTime()) &&
                            !duration.getStartTime().isBefore(currentDuration.getStartTime())) {
                        foundInvalidCombination = true;
                    }
                } else {
                    if (!isAfterFirstOrEqual(currentDuration.getEndTime(), duration.getStartTime()) &&
                            isAfterFirstOrEqual(currentDuration.getStartTime(), duration.getEndTime())) {
                        foundInvalidCombination = true;
                    }
                }
            }
        }
        return !foundInvalidCombination;
    }

    private boolean isAfterFirstOrEqual(LocalDateTime first, LocalDateTime second) {
        return second.isAfter(first) || second.isEqual(first);
    }
}
@@ -840,57 +840,8 @@
   %7D%0A
-        boolean foundInvalidCombination = false;%0A
     
@@ -953,16 +953,16 @@
 ame());%0A
+
         
@@ -1281,37 +1281,19 @@
     
-foundInvalidCombination = tru
+return fals
 e;%0A 
@@ -1598,37 +1598,19 @@
     
-foundInvalidCombination = tru
+return fals
 e;%0A 
@@ -1892,37 +1892,19 @@
     
-foundInvalidCombination = tru
+return fals
 e;%0A 
@@ -1985,32 +1985,12 @@
 urn 
-!foundInvalidCombination
+true
 ;%0A  

simplify validation logic