package org.itevents.mybatis.mapper.util;

import org.apache.ibatis.jdbc.SQL;
import org.itevents.parameter.FilteredEventsParameter;

public class SQLBuilder {

    public String selectFilteredEvent(final FilteredEventsParameter params) {
        return new SQL() {{
            SELECT("*");
            FROM("events e");
            if (params.getCity() != null) {
                WHERE("city_id = #{city.id}");
            }
            if (params.getCity() == null && (params.getLatitude() != null)) {
                WHERE("ST_DWithin((point)::geography, ST_MakePoint(#{longitude},#{latitude})::geography, #{radius})");
            }
            if (params.getFree() != null) {
                WHERE("free = #{free}");
            }
            if (params.getTechnologies() != null) {
                JOIN(makeJoin(params));
            }
        }}.toString();
    }

    private String makeJoin(FilteredEventsParameter params){
        StringBuilder sb = new StringBuilder();
        sb.append("event_technology t ON ");
        for (int i = 0; i < params.getTechnologies().size(); i++) {
            sb.append("t.technology_id=");
            sb.append(params.getTechnologies().get(i).getId());
            sb.append(" and e.id=t.event_id");
            if (i < (params.getTechnologies().size() - 1)){
                sb.append(" or ");
            }
        }
        return sb.toString();
    }
}

@@ -1015,13 +1015,36 @@
 ogy 
+e
 t ON 
+e.id=et.event_id and (
 %22);%0A
@@ -1134,16 +1134,17 @@
 append(%22
+e
 t.techno
@@ -1223,55 +1223,8 @@
 ));%0A
-            sb.append(%22 and e.id=t.event_id%22);%0A
     
@@ -1320,32 +1320,32 @@
 ;%0A            %7D%0A
-
         %7D%0A      
@@ -1330,32 +1330,56 @@
     %7D%0A        %7D%0A
+        sb.append(%22)%22);%0A
         return s

fix join query