// Parse and return an LDB Request

// FUNCTIONS
//  post(body, id): Exported:
            // body: [req.body from controller]
            // id  : [req.params.id from controller - this is expected to be CRS or TIPLOC]

//  convertTiploc(TIPLOC)  : Exported: Looks up CRS, Name & STANOX for Tiploc

const log      = require('../utils/log.utils');          // Log Helper
const ldb  = require('ldbs-json')
const util = require('../utils/ldb.utils')
const san = require('../utils/sanitizer.utils')

const ldbKey   = process.env.OWL_LDB_KEY
const ldbsvKey = process.env.OWL_LDB_SVKEY

async function get(body, id){
    var cleanId = san.cleanApiEndpointTxt(id);
    var obj = await util.checkCrs(cleanId);
    try {
        var crs = obj[0]['3ALPHA'];
        log.out(`ldbService.get: Determined CRS for lookup to be: ${crs}`);
        var data = await arrDepBoard(crs);
    } catch (err) {
        log.out(`ldbService.get: Error, Unable to find CRS: ${err}`)
        var data = {ERROR:'NOT_FOUND',description:'The entered station was not found.  Please check and try again.'};
    }
    return data;
}

async function arrDepBoard(CRS){
    log.out(`ldbService.arrDepBoard: Trying to fetch ArrDep Board for ${CRS}`)
    try {
        var options = {
            numRows: 10,
            crs: CRS.toUpperCase()
        }
        var api = new ldb(ldbKey,false)
        var reply = await api.call("GetArrDepBoardWithDetails",options)
        return reply
    } catch (err) {
        log.out(`ldbService.arrDepBoard: Lookup Failed for: ${CRS}`)
        return {GetStationBoardResult: "not available", Reason: `The CRS code ${CRS} is not valid`, Why: `Sometimes a station will have more than one CRS - for example Filton Abbey Wood has FIT and FAW however schedules are only available when looking up with FIT - this is how the National Rail Enquiries systems work.`};
    }
};

module.exports = {
    get
}