<commit_before>
require "sinatra"
require "sinatra/json"
require "nominatim"
require "psych"
require "httparty"

require_relative "email"
require_relative "address"

class LocationInterface < Sinatra::Base


    helpers Sinatra::JSON

    before do
        parse_config
    end

    error Exception do
        puts "argh"
        exit 1
    end

    get "/" do
        "Nya."
    end

    # Arguments:
    # - address
    # - city
    # - postal_code
    #
    # Either address or postal code is required, not both.
    post "/geocode" do
        address_string = "#{params["address"]}, #{params["postal_code"]} #{params["city"]}"
        places = Nominatim.search(address_string).limit(1).address_details(true)
        raise "No restaurants" if places.count < 1

        place = places.each.next

        hash = { latitude: place.lat, longitude: place.lon }
        json hash
    end

    # Arguments:
    # - latitude
    # - longitude
    post "/reverse" do
        place = Nominatim.reverse(params["latitude"], params["longitude"]).address_details(true).fetch
        raise "Nothing found for given coordinates" if place.nil?
        address = place.address
        if not address.road
            Email.send( {
                from: "<EMAIL>",
                to: "<EMAIL>",
                subject: "Road in Nominatim result instead of street",
                message: "For some reason Nominatim result had road instead of street in the response. Debug this: #{place.inspect}"
            })
            raise "Road not set in response. Response: #{place.inspect}"
        end
        hash = { "address" => "#{address.road} #{address.house_number}", "city" => address.city, "postal_code" => address.postcode }
        json hash
    end

    # distance from dot a to dot b over air
    post "/distance" do
        raise "Not implemented"
    end


    # Arguments:
    # - from["address"]
    # - from["postal_code"]
    # - from["city"]
    # - from["latitude"]
    # - from["longitude"]
    # - to["address"]
    # - to["postal_code"]
    # - to["city"]
    # - to["latitude"]
    # - to["longitude"]
    #
    # For address, atleast postal code or city must be given, otherwise the result is not
    # accurate.
    #
    # If both address and coordinates are given, coordinates are preferred over address.
    #
    # Internally, address will be converted to coordinates and then routed using coordinates.
    post "/distance_by_roads" do
        if params["from"].nil? or params["to"].nil?
            raise "Invalid input."
        end

        from = {}
        to = {}
        puts params
        unless params["from"]["latitude"].nil?
            from["latitude"] = params["from"]["latitude"]
            from["longitude"] = params["from"]["longitude"]
        else
            from["latitude"], from["longitude"] = address_to_coordinates params["from"]
        end

        unless params["to"]["latitude"].nil?
            to["latitude"] = to["to"]["latitude"]
            to["longitude"] = to["to"]["longitude"]
        else
            to["latitude"], to["longitude"] = address_to_coordinates params["to"]
        end

        config = Psych.load_file "config/config.yaml"
        uri = "#{config["osrm"]["service_url"]}/viaroute?loc=#{from["latitude"]}," +
                "#{from["longitude"]}&loc=#{to["latitude"]},#{to["longitude"]}"
        response = HTTParty.get uri

        body = JSON.parse response.body
        json body["route_summary"]["total_distance"]
    end

    private

    def address_to_coordinates address
        split_address = Address.split_street(address["address"])<commit_msg>Actually take coordinates from the array...<commit_after>
require "sinatra"
require "sinatra/json"
require "nominatim"
require "psych"
require "httparty"

require_relative "email"
require_relative "address"

class LocationInterface < Sinatra::Base


    helpers Sinatra::JSON

    before do
        parse_config
    end

    error Exception do
        puts "argh"
        exit 1
    end

    get "/" do
        "Nya."
    end

    # Arguments:
    # - address
    # - city
    # - postal_code
    #
    # Either address or postal code is required, not both.
    post "/geocode" do
        address_string = "#{params["address"]}, #{params["postal_code"]} #{params["city"]}"
        places = Nominatim.search(address_string).limit(1).address_details(true)
        raise "No restaurants" if places.count < 1

        place = places.each.next

        hash = { latitude: place.lat, longitude: place.lon }
        json hash
    end

    # Arguments:
    # - latitude
    # - longitude
    post "/reverse" do
        place = Nominatim.reverse(params["latitude"], params["longitude"]).address_details(true).fetch
        raise "Nothing found for given coordinates" if place.nil?
        address = place.address
        if not address.road
            Email.send( {
                from: "<EMAIL>",
                to: "<EMAIL>",
                subject: "Road in Nominatim result instead of street",
                message: "For some reason Nominatim result had road instead of street in the response. Debug this: #{place.inspect}"
            })
            raise "Road not set in response. Response: #{place.inspect}"
        end
        hash = { "address" => "#{address.road} #{address.house_number}", "city" => address.city, "postal_code" => address.postcode }
        json hash
    end

    # distance from dot a to dot b over air
    post "/distance" do
        raise "Not implemented"
    end


    # Arguments:
    # - from["address"]
    # - from["postal_code"]
    # - from["city"]
    # - from["latitude"]
    # - from["longitude"]
    # - to["address"]
    # - to["postal_code"]
    # - to["city"]
    # - to["latitude"]
    # - to["longitude"]
    #
    # For address, atleast postal code or city must be given, otherwise the result is not
    # accurate.
    #
    # If both address and coordinates are given, coordinates are preferred over address.
    #
    # Internally, address will be converted to coordinates and then routed using coordinates.
    post "/distance_by_roads" do
        if params["from"].nil? or params["to"].nil?
            raise "Invalid input."
        end

        from = {}
        to = {}
        unless params["from"]["latitude"].nil?
            from["latitude"] = params["from"]["latitude"]
            from["longitude"] = params["from"]["longitude"]
        else
            from["latitude"], from["longitude"] = address_to_coordinates params["from"]
        end

        unless params["to"]["latitude"].nil?
            to["latitude"] = params["to"]["latitude"]
            to["longitude"] = params["to"]["longitude"]
        else
            to["latitude"], to["longitude"] = address_to_coordinates params["to"]
        end

        config = Psych.load_file "config/config.yaml"
        uri = "#{config["osrm"]["service_url"]}/viaroute?loc=#{from["latitude"]}," +
                "#{from["longitude"]}&loc=#{to["latitude"]},#{to["longitude"]}"
        response = HTTParty.get uri

        body = JSON.parse response.body
        json body["route_summary"]["total_distance"]
    end

    private

    def address_to_coordinates address
        split_address = Address.split_street(address["address"])
{'fraction_non_alphanumeric': 0.13284691629955947, 'fraction_numerical': 0.0008259911894273128, 'mean_word_length': 2.3279890059551076, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 13, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '781877', 'n_tokens_mistral': 2118, 'n_tokens_neox': 2077, 'n_words': 548}