Promise = require 'bluebird'
co = require 'co'
xml2js = require("xml2js")
_ = require 'lodash'

log = require './log'

xmlBuilder = new xml2js.Builder(rootName: 'xml', headless: true)
parseXMLString = Promise.promisify xml2js.parseString.bind(xml2js)

exports.parseInt = (string, alternative)->
    try
        r = parseInt string, 10
        if _.isNaN(r) then return alternative else return r
    catch
        alternative || null

exports.objectToXML = (object)-> xmlBuilder.buildObject(object)

exports.pParseXML = parseXMLString

exports.setTimeout = (timeout, run)-> setTimeout(run, timeout)
exports.setGeneratorTimeout = (timeout, run)->
    run2 = -> co(run).catch (e)-> log.system.error e
    setTimeout(run2, timeout)

exports.setGeneratorInterval = (timeout, run)->
    run2 = -> co(run).catch (e)-> log.system.error e
    setInterval(run2, timeout)
