/*
 * Copyright (c) 2017. Vitus Lehner. UrbanLife+. Universität der Bundeswehr München.
 */

package org.sociotech.urbanlifeplus.microinforadiator.service;

import org.sociotech.urbanlifeplus.microinforadiator.interfaces.light.LightColor;
import org.sociotech.urbanlifeplus.microinforadiator.interfaces.light.LightInterface;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Optional;

/**
 * Service to update the lighting interfaces. Light colors applied to this service are automatically
 * broadcasted to all light interfaces.
 *
 * @author vituslehner 03.07.17
 */
@Service
public class LightService {

    private final Collection<LightInterface> lightInterfaces;
    private final Collection<LightColor> currentColors;

    @Autowired
    public LightService(Collection<LightInterface> lightInterfaces) {
        this.lightInterfaces = lightInterfaces;
        this.currentColors = new HashSet<>();

        notifyInterfaces();
    }

    /**
     * Add a color to the lights.
     *
     * @param color the color
     */
    public void addColor(LightColor color) {
        currentColors.add(color);
        notifyInterfaces();
    }

    /**
     * Remove a color from the lights.
     *
     * @param color the color
     */
    public void removeColor(LightColor color) {
        currentColors.remove(color);
        notifyInterfaces();
    }

    /**
     * Returns an {@link Optional} that contains a color that is not in use yet.
     *
     * @return a spare color
     */
    public Optional<LightColor> acquireSpareColor() {
        return Arrays.stream(LightColor.values())
                .filter(lightColor -> !currentColors.contains(lightColor))
                .findFirst();
    }

    /**
     * Notify light interfaces about changes.
     */
    private void notifyInterfaces() {
        lightInterfaces.forEach(lightInterface -> lightInterface.setColors(currentColors));
    }

    public Collection<LightColor> getCurrentColors() {
        return currentColors;
    }
}

@@ -146,24 +146,81 @@
 r.service;%0A%0A
+import org.slf4j.Logger;%0Aimport org.slf4j.LoggerFactory;%0A
 import org.s
@@ -816,16 +816,103 @@
 vice %7B%0A%0A
+    private final static Logger LOGGER = LoggerFactory.getLogger(LightService.class);%0A%0A
     priv
@@ -2131,16 +2131,17 @@
 forEach(
+(
 lightInt
@@ -2146,19 +2146,56 @@
 nterface
+)
  -%3E
+ %7B%0A            try %7B%0A               
  lightIn
@@ -2226,16 +2226,173 @@
 tColors)
+;%0A            %7D catch (Exception e) %7B%0A                LOGGER.error(%22Failed to notify light interface about light color changes.%22, e);%0A            %7D%0A        %7D
 );%0A    %7D

Handle light interface exceptions