var express = require('express')
, http      = require('http')
, log       = require('./log')
, path      = require('path')
, request   = require('request')
, xml       = require('xml2js').parseString

var app     = express()
var stops   = require('../data/stops')

var extract_data = function (data, cb) {
  xml(data, function (err, res) {
    if (err) {
      return cb(err, null)
    }

    var result    = {}
    , data_body   = res['soap:Envelope']['soap:Body'][0]

    if (data_body === undefined || data_body.getUserRealTimeForecastExByStopResponse === undefined) {
      cb({message:'no data', name:'', lat:'', lon:'', next:[]})
      return
    }

    var data_response = data_body.getUserRealTimeForecastExByStopResponse[0]
    , data_result     = data_response.getUserRealTimeForecastExByStopResult[0]

    if (data_result == 'WsAuthenticationError') {
      cb({error: 'WsAuthenticationError'})
      return
    }

    var data          = JSON.parse(data_result)
    , info            = data.InfoNodo[0]

    result.name       = info.descrNodo
    result.lat        = info.coordLon
    result.lon        = info.coordLat

    result.next       = []

    data.Orari.forEach(function (departure) {
      result.next.push({
        l:   departure.codAzLinea,
        t:   departure.orario,
        ts:  departure.orarioSched,
        rt:  departure.statoPrevisione == 'Prev' ? 1 : 0,
        d:   departure.capDest
      })
    })

    cb(null, result)
  })
}


/* Routes
----------------------------------------------------------------------------- */

module.exports = function (options) {
  log('Starting...')

  app.get('/oracle/:query', function (req, res) {
    request('http://m.atb.no/xmlhttprequest.php?service=routeplannerOracle.getOracleAnswer&question=' + req.params.query, function (err, response, body) {
      if (err) {
        return res.json({error:'Ops, somthing went wrong'})
      }

      if (response.statusCode == 200) {
        body = body.replace(/\n/g, '')
        body = body.replace(/([a-zA-Z])\.([a-zA-Z])/g, '$1.<br>$2')
        res.send(body)
      }
    })
  })

  app.get('/rt/:stopid', function (req, res){
    if (options.user === '' || options.pass === '') {
      return res.json({error:'Webservice username and password missing'})
    }

    if (/\D/.test(req.params.stopid)) {
      return res.json({error:'Not a valid stopid'})
    }

    var env = '<?xml version="1.0" encoding="utf-8"?><soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://schemas.xmlsoap.org/soap/envelope/"><soap12:Body><getUserRealTimeForecastExByStop xmlns="http://miz.it/infotransit"><auth><user>'+ options.user +'</user><password>'+ options.pass +'</password></auth><busStopId>' + req.params.stopid + '</busStopId><nForecast>20</nForecast></getUserRealTimeForecastExByStop></soap12:Body></soap12:Envelope>'

    var post_request = {
      host: 'st.atb.no',
      path: '/InfoTransit/userservices.asmx',
      port: 80,
      method: 'POST',
      headers: {
        'Cookie': 'cookie',
        'Content-Type': 'text/xml;charset="utf-8"',
        'SOAPAction': 'http://miz.it/infotransit/getUserRealTimeForecastExByStop',
        'Content-Length': Buffer.byteLength(env)
      }
    }

    var request = http.request( post_request, function (r) {
      var buffer = ''

      r.on( "data", function( data ) {
        buffer = buffer + data
      })

      r.on( "end", function( data ) {
        extract_data(buffer, function (err, data) {
          if (err) {
            res.json({error: 'Something went wrong'})
          }

          res.json(data)
        })
      })
    })

    request.write( env )
    request.end()
  })

  app.get('/stops', function (req, res) {
    res.json(stops.stops)
  })

  return app;
}

process.on('uncaughtException', function (err) {
  log(err.stack)
})

@@ -1554,17 +1554,16 @@
 ---- */%0A
-%0A
 module.e
@@ -2140,16 +2140,17 @@
 eq, res)
+ 
 %7B%0A    if
@@ -2767,16 +2767,114 @@
 %3C/auth%3E%3C
+handShakeUser%3E%3Cuser%3Etmn%3C/user%3E%3Ctoken%3Etmn-best%3C/token%3E%3Cresponse%3ESuccess%3C/response%3E%3C/handShakeUser%3E%3C
 busStopI
@@ -3070,16 +3070,20 @@
 path: '/
+New/
 InfoTran
@@ -3223,16 +3223,17 @@
 ext/xml;
+ 
 charset=
@@ -3246,91 +3246,8 @@
 %22',%0A
-        'SOAPAction': 'http://miz.it/infotransit/getUserRealTimeForecastExByStop',%0A
     
@@ -3337,17 +3337,16 @@
 request(
- 
 post_req
@@ -3404,15 +3404,14 @@
 .on(
- %22
+'
 data
-%22
+'
 , fu
@@ -3408,39 +3408,38 @@
 'data', function
-(
  
+(
 data
- 
 ) %7B%0A        buff
@@ -3482,14 +3482,13 @@
 .on(
- %22end%22
+'end'
 , fu
@@ -3497,15 +3497,14 @@
 tion
-(
  
+(
 data
- 
 ) %7B%0A
@@ -3714,21 +3714,19 @@
 t.write(
- 
 env
- 
 )%0A    re
@@ -3829,17 +3829,16 @@
 turn app
-;
 %0A%7D%0A%0Aproc

Update API version