text: /* Copyright 2021 Planet Labs Inc.
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *     http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  
  /** Collection of functions used for styling tile data.
   *  @module stylefunc
   */
  
  import * as maths from './maths';
  import {Parser} from 'expr-eval';
  
  const styleFuncs = {...maths.styleFuncs};
  
  export function testUserFunctions(functions, results = {}) {
    // check for a basic RGBA image
    const bands = [128, 64, 100, 255];
    const vmin = [0, 0, 0, 0];
    const vmax = [255, 255, 255, 255];
  
    const bandmap = {
      r: 2,
      g: 1,
      b: 0,
      a: 3,
    };
  
    for (let x = 0, xx = functions.length; x < xx; x++) {
      const [name, fn] = functions[x];
      results[name] = fn.evaluate({bands, vmin, vmax, results, bandmap});
    }
  
    if (
      results.red === undefined ||
      results.green === undefined ||
      results.blue === undefined
    ) {
      throw new Error('Failed to get red, green, or blue.');
    }
  }
  
  /* Hulk smashes big monsters.
   * This is *not* an exhastive list of variables
   * that should be kept out of scope but these are definitely known
   * offenders.
   */
  function hulkSmash(statements) {
    const monsters = [
      'new ',
      'window',
      'fetch',
      'global',
      'document',
      'alert',
      'confirm',
      'Math',
    ].map(monster => new RegExp(monster, 'ig'));
  
    // copy the statements to a fresh string
    let smashed = '' + statements;
    // smash each monster.
    monsters.forEach(monster => {
      smashed = smashed.replace(monster, '');
    });
    return smashed;
  }
  
  export function compileUserFunction(statements, options) {
    // create a new equation parser.
    const parser = new Parser();
  
    // convert all the statements into Javascript functions.
    const functions = hulkSmash(statements)
      .split('\n')
      .filter(
        line => line.length > 0 && line[0] !== '#' && line.indexOf(':=') > 0
      )
      .map(eq => {
        const [name, expr] = eq.split(':=').map(v => v.trim());
        // expr-eval also has a toJSFunction method.
        // In testing, parse + evaluate was _faster_ than the
        // functions generated by toJSFunction.
        // Using parse + evaluate should also be safer.
        const fn = parser.parse(expr);
        return [name, fn];
      });
  
    // These are offered to the user to make it easier to
    //  properly normalize the band values.
    const vmin = options.ranges.map(r => r[0]);
    const vmax = options.ranges.map(r => r[1]);
  
    testUserFunctions(functions);
  
    // using this closure prevents re-calculating the loop length
    //  during every pixel draw.
    const nFunctions = functions.length;
    return (bands, bandmap) => {
      const results = {};
      for (let x = 0; x < nFunctions; x++) {
        const [name, fn] = functions[x];
        results[name] = fn.evaluate({bands, vmin, vmax, results, bandmap});
      }
      bands[0] = Math.floor(results.red);
      bands[1] = Math.floor(results.green);
      bands[2] = Math.floor(results.blue);
      // use alpha is it comes back from the user,
      //  otherwise normalize it from the band values.
      if (results.alpha) {
        bands[3] = Math.floor(results.alpha);
      } else {
        const alpha = bands[bandmap.a];
        bands[3] = alpha ? 255 : 0;
      }
    };
  }
  
  /** Primary function for creating a new style function
   *
   * @param {string} funcName - The basic rendering function for the data
   *                   Valid values are: rgb, lut, grey, onlyRed, pending, value
   * @param {Object} options
   * @param {array} [options.ranges] - 2D array of [[minValue, maxValue], ...] in band order.
   * @param {array} [options.lut] - Used for lookup table styling. 2D array of [[0, .., max], ...] in band order, uses 0-255 as the output values.
   * @param {array} [options.curves] - 2D array of [[min, ..., max], ...] in band order, uses 0-1 floating point values to curve the data.
   * @param {number} [options.pixelDepth] - The maximum value for an individual band in a pixel.
   * @param {array} [options.bcs] - [brightness, contrast, saturation]. A value of 1 is the identity all others shift the coloration based on a Brightness, Contrast, Saturation matrix.
   *
   * @returns {Function} The style function.
   */
  export function createStyleFunc(funcName, options) {
    let colorFn = null;
    if (funcName === 'user') {
      if (!options.statements) {
        throw new Error('User functions require the "statements" option.');
      }
      if (!options.ranges) {
        throw new Error('User functions require the "ranges" option.');
      }
      colorFn = compileUserFunction(options.statements, options);
    } else if (funcName === 'lut') {
      colorFn = maths.lookupTableStyle(options.lut, options.ranges);
    } else if (styleFuncs[funcName]) {
      colorFn = styleFuncs[funcName];
    } else {
      // Default to the "value" style which returns
      //  the first band as RGB
      colorFn = styleFuncs.value;
    }
  
    const fn = [];
  
    if (options.curves) {
      fn.push(maths.applyCurves(options.curves, options.pixelDepth));
    }
  
    if (options.bcs) {
      fn.push(maths.applyBrightnessContrastSaturation(...options.bcs));
    }
  
    if (funcName !== 'user' && funcName !== 'lut' && options.pixelDepth !== 256) {
      const scale = 256 / options.pixelDepth;
      fn.push(pixel => {
        for (let i = 0; i < 3; i++) {
          pixel[i] = pixel[i] * scale;
        }
        return pixel;
      });
    }
  
    fn.push(colorFn);
  
    // user defined function for adjusting the raster
    //  after the other operations have finished.
    if (options.postStatements && options.ranges) {
      fn.push(compileUserFunction(options.postStatements, options));
    }
  
    const ii = fn.length;
    // each function will get the pixel data and the bandMaps
    const render = (px, bandMap) => {
      for (let i = 0; i < ii; i++) {
        fn[i](px, bandMap);
      }
      return px;
    };
    return render;
  }
  
  /** Flattens the numpy data and runs the style function against it.
   *
   *
   * @param data - Numpy tile data.
   * @param bandsize - The size of the band (nominally 256 * 256)
   * @param bandOffset - The 0-th location for each band.
   * @param bandMap - An object mapping the band-names to band indexes
   * @param rgbaFunc - A function which inputs the pixel data and sets rgba values.
   */
  export function processData(data, bandsize, bandOffset, bandMap, rgbaFunc) {
    const nBands = bandOffset.length;
    const res = new Uint8ClampedArray(4 * bandsize);
    // 8-band capable.
    const bandData = new Array(nBands);
    for (let b = 0; b < bandsize; b++) {
      for (let i = 0; i < nBands; i++) {
        bandData[i] = data[b + bandOffset[i]];
      }
      rgbaFunc(bandData, bandMap);
      const offset = b * 4;
      res[offset] = bandData[0];
      res[offset + 1] = bandData[1];
      res[offset + 2] = bandData[2];
      res[offset + 3] = bandData[3];
    }
    return res;
  }
  
  /** Converts the band-sorted numpy tile into a flat-ImageData like array.
   *
   * @param rgbaFunc - Function to take in all bands and set them to rgba
   * @param data - The data portion of the numpytile
   */
  export function drawArray(styleFunc, data, bands) {
    const bandMap = {};
    const bandOffset = [];
    const bandsize = 256 * 256;
  
    const inBands = bands.slice();
    if (inBands.indexOf('a') < 0) {
      inBands.push('a');
    }
  
    for (let i = 0, ii = inBands.length; i < ii; i++) {
      bandOffset.push(i * bandsize);
      bandMap[inBands[i]] = i;
    }
    return processData(data, bandsize, bandOffset, bandMap, styleFunc);
  }
  
  /** Draw the numpy data.
   *
   * @param canvas - A canvas on which to draw.
   * @param npyTile - The numpy tile.
   * @param dtype - The data-type (uint16, byte) in the numpy tile.
   * @param bands - Order of the bands as they are laid out in the numpy tile.
   * @param rgbaFunc - A function which computes RGBA from the data.
   */
  export function draw(canvas, npyTile, dtype, bands, rgbaFunc) {
    const res = drawArray(rgbaFunc, npyTile.data, bands);
    const ctx = canvas.getContext('2d');
    const imgData = ctx.createImageData(256, 256);
    imgData.data.set(res);
    ctx.putImageData(imgData, 0, 0);
  }
  