const log  = require('../utils/log.utils');            // Log Helper
const db   = require('../services/dbAccess.services') // DB Access
const san  = require('../utils/sanitizer.utils')     // Sanitiser

async function checkCrs(input){
    var INPUT = input.toUpperCase()
    log.out(`ldbUtils.checkCrs: Building database query to find: '${INPUT}'`)
    var query = {'$or':[{'3ALPHA':INPUT},{'TIPLOC':INPUT},{'STANOX':INPUT}]};
    var result = await db.query("stations", query)
    log.out(`ldbUtils.checkCrs: Query results: ${JSON.stringify(result)}`)
    return result
}

async function cleanMessages(input){
    var out = []
    if (typeof input.message == "string") {
        out.push(await san.cleanNrcc(input.message))
    } else if (typeof input.message == "object") {
        for(var i = 0; i < input.message.length; i++) {
            out.push(await san.cleanNrcc(input.message[i]))
        }
    }
    return out;
}

// Accepts an object but not an Array and returns it wrapped in an array.
async function cleanServices(input){
    var out = []
    if (!Array.isArray(input)) {
        log.out(`ldbUtils.cleanServices: Transforming input: ${input}`)
        out.push(input)
        log.out(`ldbUtils.cleanServices: Returning output: ${out}`)
        return out;
    } else {
        return input;
    }
}

module.exports = {
    checkCrs,
    cleanMessages,
    cleanServices
}