 express = require('express')
 _ = require('underscore')
+config = require 'config'
+http = require 'http'
 
 app = express()
 


    specs.municipality = extractMunicipality(req)
    specs.services = extractServices(req)
    specs.address = extractStreetAddress(req)
    if specs.address != null
        specs.serviceCategory = dig('service')
    specs

        path.push specs.unit
    protocol + path.join('/') + generateQuery(specs, resource, originalUrl) + fragment


getMunicipalityFromGeocoder = (address, language, callback) ->
    municipality = address.municipality
    if municipality? and municipality.length
        callback municipality
        return

    timeout = setTimeout (-> callback null), 3000

    url = "#{config.service_map_backend}/address/?language=#{language}&number=#{address.number}&street=#{address.street}&page_size=1"
    request = http.get url, (apiResponse) ->
        if apiResponse.statusCode != 200
            clearTimeout timeout
            callback null
            return
        respData = ''
        apiResponse.on 'data', (data) ->
            respData += data
        apiResponse.on 'end', ->
            addressInfo = JSON.parse respData
            clearTimeout timeout
            municipality = addressInfo?.results?[0]?.street?.municipality
            callback municipality
            return
    request.on 'error', (error) =>
        console.error 'Error geocoding using servicemap API', error
        callback null
        return

redirector = (req, res) ->
    specs = extractSpecification(req)
    resource = getResource specs
    if resource == 'address' and not specs.address.municipality?
        getMunicipalityFromGeocoder specs.address, specs.language.id, (municipality) ->
            if municipality?
                specs.address.municipality = municipality
            else
                specs.address.municipality = 'helsinki'
            url = generateUrl(specs, req.originalUrl)
            res.redirect 301, url
        return
    else
        url = generateUrl(specs, req.originalUrl)
        res.redirect 301, url
        return

module.exports = redirector
