const fs = require('fs-extra'), path = require('path'), utils = require('./utils'), polyUtil = require('./poly_util'), FILE = require('./file_constants'), debug = require('debug')('agm:file_satlog'); const POL = ".POL"; const PAT = ".PAT"; const INC = "INC"; const EXC = "EXC"; const SWIDTH = "SWIDTH"; function getItem(val, pos) { return val[pos] ? val[pos].trim() : ''; } function readSatLogJob(filePath, areaTypeAndFiles, ops, cb) { let firstCol, fields, lat, lon, valueF, swath = 0, isMetric = false, newPolygon = false, sprayPoly = false; let cornerSets = [], sprayAreas = [], xclAreas = []; const bareFilename = utils.normalizeName(utils.bareFilename(areaTypeAndFiles.area)); return fs.readFile(path.join(filePath, areaTypeAndFiles.area)) .then((data) => { let areas, lines = data.toString().split("\n"); for (const i in lines) { if (sprayAreas.length >= FILE.MAX_ITEM || xclAreas.length >= FILE.MAX_ITEM) break; fields = lines[i].trim().split(new RegExp('\\s+')); firstCol = getItem(fields, 0); if (!firstCol.length) continue; if (firstCol === POL || firstCol === PAT || i == lines.length - 1) { newPolygon = (firstCol === POL) ? true : false; if (cornerSets.length >= 3) { if (sprayPoly) { areas = polyUtil.createAreas(0, cornerSets, bareFilename, ops.sprZoneColor, ops.appRate, ops.crop); if (sprayAreas.length < FILE.MAX_ITEM && !utils.isEmptyArray(areas)) sprayAreas = sprayAreas.concat(areas); } else { areas = polyUtil.createAreas(1, cornerSets, 'XCL'); if (xclAreas.length < FILE.MAX_ITEM && !utils.isEmptyArray(areas)) xclAreas = xclAreas.concat(areas); } } cornerSets = []; continue; } if (newPolygon) { if (firstCol === INC || firstCol === EXC) { sprayPoly = (firstCol === INC) ? true : false; } else { if (fields.length === 2) { lat = parseFloat(getItem(fields, 0)); lon = parseFloat(getItem(fields, 1)); if (utils.isNumber(lat) && utils.isNumber(lon)) { cornerSets.push([lon, lat]); // Revert coor order in GeoJSON } } } } else { if (firstCol === SWIDTH && fields.length > 1) { valueF = parseFloat(getItem(fields, 1)); if (utils.isNumber(valueF)) swath = valueF; if (fields.length >= 3) { isMetric = (getItem(fields, 3)).toUpperCase() === 'M' ? true : false; } continue; } } } const jobItem = { sprayAreas: sprayAreas, xclAreas: xclAreas, meta: { measureUnit: isMetric, swath: swath } }; if (!utils.isEmptyArray(xclAreas)) { jobItem['xclAreas'] = polyUtil.processXclsName(jobItem.sprayAreas, jobItem.xclAreas); } if (cb) cb(null, jobItem); else return jobItem; }) .catch(err => { if (cb) return cb(err); else throw err; }); } module.exports = { readSatLogJob }