package fi.nls.oskari.routing;

import com.ibatis.common.resources.Resources;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;
import org.postgis.Geometry;
import org.postgis.PGgeometry;

import java.io.Reader;
import java.util.ArrayList;
import java.util.List;

public class RoutingService {
    private SqlMapClient client = null;
    private static String SQL_MAP_LOCATION = "META-INF/SqlMapConfig.xml";

    private SqlMapClient getSqlMapClient() {
        if (client != null) { return client; }

        Reader reader = null;
        try {
            reader = Resources.getResourceAsReader(SQL_MAP_LOCATION);
            client = SqlMapClientBuilder.buildSqlMapClient(reader);
            return client;
        } catch (Exception e) {
            throw new RuntimeException("Failed to retrieve SQL client", e);
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

    public Long hevonen() {
        try {
            SqlMapClient client = getSqlMapClient();
            Long results = (Long)client.queryForObject("Routing.foo");
            return results;
        } catch (Exception e) {
            System.out.println(e.getMessage());
            throw new RuntimeException("Failed to query", e);
        }
    }

    public List<Geometry> calculateRoute() {
        try {
            SqlMapClient client = getSqlMapClient();
            List results = client.queryForList("Routing.calculateRoute");
            List<Geometry> output = new ArrayList<Geometry>();
            for (Object result : results) {
                PGgeometry lol = (PGgeometry) result;
                output.add(lol.getGeometry());
            }
            return output;
        } catch (Exception e) {
            System.out.println(e.getMessage());
            throw new RuntimeException("Failed to query", e);
        }
    }
}

@@ -1582,82 +1582,8 @@
 ();%0A
-            List results = client.queryForList(%22Routing.calculateRoute%22);%0A
     
@@ -1605,22 +1605,23 @@
 ometry%3E 
-output
+results
  = new A
@@ -1671,23 +1671,58 @@
 ct r
-esult : results
+ow : client.queryForList(%22Routing.calculateRoute%22)
 ) %7B%0A
@@ -1748,19 +1748,24 @@
 eometry 
-lol
+geometry
  = (PGge
@@ -1773,21 +1773,18 @@
 metry) r
-esult
+ow
 ;%0A      
@@ -1797,22 +1797,28 @@
     
-output.add(lol
+results.add(geometry
 .get
@@ -1867,14 +1867,15 @@
 urn 
-output
+results
 ;%0A  

Improve naming