// -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; -*-
// vim: et ts=4 sts=4 sw=4 syntax=java
package com.aragaer.jtt.astronomy;

import java.util.Calendar;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;

import com.luckycatlabs.sunrisesunset.SunriseSunsetCalculator;
import com.luckycatlabs.sunrisesunset.dto.Location;


public  class SscAdapter implements SolarEventCalculator {
    private final LocationHandler _locationHandler;

    public SscAdapter(LocationHandler locationHandler) {
        _locationHandler = locationHandler;
    }

    @Override public Calendar getSunriseFor(Calendar noon) {
        float[] location = _locationHandler.getLocation();
        SunriseSunsetCalculator calculator = getCalculatorForLocation(location[0], location[1]);
        return calculator.getOfficialSunriseCalendarForDate((Calendar) noon.clone());
    }

    @Override public Calendar getSunsetFor(Calendar noon) {
        float[] location = _locationHandler.getLocation();
        SunriseSunsetCalculator calculator = getCalculatorForLocation(location[0], location[1]);
        return calculator.getOfficialSunsetCalendarForDate((Calendar) noon.clone());
    }

    private SunriseSunsetCalculator getCalculatorForLocation(float latitude, float longitude) {
        int offsetMillis = (int) TimeUnit.HOURS.toMillis(Math.round(longitude/15));
        return new SunriseSunsetCalculator(new Location(latitude, longitude),
                                           getTimeZone(offsetMillis));
    }

    private static TimeZone getTimeZone(int offsetMillis) {
        for (String tzName : TimeZone.getAvailableIDs(offsetMillis)) {
            TimeZone tz = TimeZone.getTimeZone(tzName);
            if (!tz.useDaylightTime())
                return tz;
        }
        throw new RuntimeException("Failed to find timezone for offset "+offsetMillis);
    }
}

@@ -631,490 +631,188 @@
     
-float%5B%5D location = _locationHandler.getLocation();%0A        SunriseSunsetCalculator calculator = getCalculatorForLocation(location%5B0%5D, location%5B1%5D);%0A        return calculator.getOfficialSunriseCalendarForDate((Calendar) noon.clone());%0A    %7D%0A%0A    @Override public Calendar getSunsetFor(Calendar noon) %7B%0A        float%5B%5D location = _locationHandler.getLocation();%0A        SunriseSunsetCalculator calculator = getCalculatorForLocation(location%5B0%5D, location%5B1%5D);%0A        return calculator
+return getCalculator().getOfficialSunriseCalendarForDate((Calendar) noon.clone());%0A    %7D%0A%0A    @Override public Calendar getSunsetFor(Calendar noon) %7B%0A        return getCalculator()
 .get
@@ -927,54 +927,71 @@
 ator
-ForLocation(float latitude, f
+() %7B%0A        float%5B%5D location = _
 lo
+c
 at
- longitude) %7B
+ionHandler.getLocation();
 %0A   
@@ -1057,23 +1057,25 @@
 round(lo
-ngitude
+cation%5B1%5D
 /15));%0A 
@@ -1134,26 +1134,31 @@
 on(l
+oc
 ati
-tude, longitude
+on%5B0%5D, location%5B1%5D
 ),%0A 

Remove duplicate code.