/**
 * Copyright (c) 2014-2016 by the respective copyright holders.
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 */
package org.openhab.binding.astro.discovery;

import static org.openhab.binding.astro.AstroBindingConstants.*;

import java.io.IOException;

import org.apache.commons.lang.StringUtils;
import org.eclipse.smarthome.config.discovery.AbstractDiscoveryService;
import org.eclipse.smarthome.config.discovery.DiscoveryResultBuilder;
import org.eclipse.smarthome.core.thing.ThingTypeUID;
import org.eclipse.smarthome.core.thing.ThingUID;
import org.eclipse.smarthome.io.net.http.HttpUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.collect.ImmutableSet;

/**
 * The {@link AstroDiscoveryService} tries to automatically discover the geolocation based on the internet IP address.
 *
 * @author Gerhard Riegler
 */
public class AstroDiscoveryService extends AbstractDiscoveryService {
    private static final Logger logger = LoggerFactory.getLogger(AstroDiscoveryService.class);
    private static final int DISCOVER_TIMEOUT_SECONDS = 30;

    /**
     * Creates a AstroDiscoveryService with disabled autostart.
     */
    public AstroDiscoveryService() {
        super(ImmutableSet.of(new ThingTypeUID(BINDING_ID, "-")), DISCOVER_TIMEOUT_SECONDS, false);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected void startScan() {
        logger.debug("Starting Astro discovery scan");
        String result = null;
        try {
            result = HttpUtil.executeUrl("GET", "http://ip-api.com/json/?fields=lat,lon", 5000);
        } catch (IOException e) {
            logger.warn("Can't get latitude and longitude for the current location: {}", e);
        }
        String lat = StringUtils.trim(StringUtils.substringBetween(result, "\"lat\":", ","));
        String lon = StringUtils.trim(StringUtils.substringBetween(result, "\"lon\":", "}"));

        try {
            Double latitude = Double.parseDouble(lat);
            Double longitude = Double.parseDouble(lon);

            logger.info("Evaluated Astro geolocation: latitude: {}, longitude: {}", latitude, longitude);

            ThingTypeUID sunType = new ThingTypeUID(BINDING_ID, SUN);
            ThingTypeUID moonType = new ThingTypeUID(BINDING_ID, MOON);

            ThingUID sunThing = new ThingUID(sunType, LOCAL);
            ThingUID moonThing = new ThingUID(moonType, LOCAL);

            String propGeolocation = String.format("%s,%s", latitude, longitude);
            thingDiscovered(DiscoveryResultBuilder.create(sunThing).withLabel("Local Sun")
                    .withProperty("geolocation", propGeolocation).build());
            thingDiscovered(DiscoveryResultBuilder.create(moonThing).withLabel("Local Moon")
                    .withProperty("geolocation", propGeolocation).build());
        } catch (Exception ex) {
            logger.warn("Can't discover Astro geolocation");
        }
    }
}

@@ -1922,24 +1922,60 @@
 ;%0A        %7D%0A
+%0A        if (result != null) %7B%0A%0A    
         Stri
@@ -2056,32 +2056,36 @@
  %22,%22));%0A        
+    
 String lon = Str
@@ -2155,38 +2155,46 @@
 %22%7D%22));%0A%0A        
+   
+ 
 try %7B%0A
+    
             Doub
@@ -2236,32 +2236,36 @@
 t);%0A            
+  
+  
 Double longitude
@@ -2289,24 +2289,28 @@
 uble(lon);%0A%0A
+    
             
@@ -2408,32 +2408,36 @@
 );%0A%0A            
+ 
+   
 ThingTypeUID sun
@@ -2478,16 +2478,20 @@
 , SUN);%0A
+    
         
@@ -2559,32 +2559,36 @@
 );%0A%0A            
+ 
+   
 ThingUID sunThin
@@ -2621,16 +2621,20 @@
 LOCAL);%0A
+    
         
@@ -2698,24 +2698,28 @@
             
+    
 String propG
@@ -2780,32 +2780,36 @@
 e);%0A            
+   
+ 
 thingDiscovered(
@@ -2883,32 +2883,36 @@
                 
+    
 .withProperty(%22g
@@ -2955,32 +2955,36 @@
 ));%0A            
+  
+  
 thingDiscovered(
@@ -3060,32 +3060,36 @@
                 
+    
 .withProperty(%22g
@@ -3128,32 +3128,36 @@
 ild());%0A        
+ 
+   
 %7D catch (Excepti
@@ -3161,24 +3161,28 @@
 ption ex) %7B%0A
+    
             
@@ -3226,24 +3226,38 @@
 location%22);%0A
+            %7D%0A
         %7D%0A  

Fix NPE in AstroDiscovery service. (#1508)