package com.buildlight.application;

import com.buildlight.respository.bamboo.api.BambooRepository;
import com.buildlight.respository.bamboo.model.BambooBuildResponse;
import com.buildlight.respository.bamboo.model.Result;
import com.cleware.driver.TrafficLight;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author zutherb
 */
@Component
public class BuildChecker {

    private TrafficLight light;
    private BambooRepository bambooRepository;

    @Autowired
    public BuildChecker(TrafficLight light, BambooRepository bambooRepository) {
        this.light = light;
        this.bambooRepository = bambooRepository;
    }

    @Scheduled(fixedDelay = 1000)
    public void changeTrafficLightLed() {
        BambooBuildResponse bambooBuildResponse = bambooRepository.getBambooBuildResponse();
        List<Result> results = bambooBuildResponse.getResults().getResults();
        Result result = results.get(0);
        BuildState state = getBuildState(result);
        light.switchOffAllLeds();
        light.switchOn(state.getLed());
    }

    private BuildState getBuildState(Result result) {
        switch (result.getState()) {
            case Unkown:
                return BuildState.Building;
            case Successful:
                return BuildState.Successful;
            case Failed:
                return BuildState.Failed;
        }
        throw new IllegalArgumentException();
    }


}

@@ -598,16 +598,62 @@
 ository;
+%0A    private BuildState lastChangedBuildState;
 %0A%0A    @A
@@ -1008,148 +1008,284 @@
     
-List%3CResult%3E results = bambooBuildResponse.getResults().getResults(
+BuildState currentBuildState = getBuildState(bambooBuildResponse);%0A        changeLedIfNessary(currentBuildState
 );%0A    
+%7D%0A%0A
     
-Result result = results.get(0);%0A        BuildState state = get
+private void changeLedIfNessary(BuildState currentBuildState) %7B%0A        if (!currentBuildState.equals(lastChangedBuildState)) %7B%0A            lastChanged
 Buil
@@ -1294,18 +1294,34 @@
 tate
-(result);%0A
+ = currentBuildState;%0A    
     
@@ -1346,24 +1346,28 @@
 fAllLeds();%0A
+    
         ligh
@@ -1377,17 +1377,29 @@
 witchOn(
-s
+currentBuildS
 tate.get
@@ -1406,16 +1406,26 @@
 Led());%0A
+        %7D%0A
     %7D%0A%0A 
@@ -1464,24 +1464,168 @@
 ate(
-Result result) %7B
+BambooBuildResponse bambooBuildResponse) %7B%0A        List%3CResult%3E results = bambooBuildResponse.getResults().getResults();%0A        Result result = results.get(0);
 %0A   

change toogle build behavior