'use strict';

var jsonParse = require('../vendor/json_parse');

var METADATA_ERROR_PREFIX = 'Something is wrong with your ISF metadata';

module.exports = function MetadataExtractor(rawFragmentShader) {
  // First pull out the comment JSON to get the metadata.
  // This regex (should) match quotes in the form /* */.
  var regex = /\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*+/;
  var results = regex.exec(rawFragmentShader);

  if (!results) {
    throw new Error('There is no metadata here.');
  }

  var metadataString = results[0];
  metadataString = metadataString.substring(1, metadataString.length - 1);
  var metadata = void 0;
  try {
    metadata = jsonParse(metadataString);
  } catch (e) {
    var loc = e.at;
    var message = e.message || 'Invalid JSON';
    if (loc) {
      var lines = (metadataString || '').substring(0, loc).split(/\r\n|\r|\n/);
      var lineNumber = lines.length;
      var position = lines[lineNumber - 1].length;
      var errorText = METADATA_ERROR_PREFIX + ': ' + message + '        at line ' + lineNumber + ' and position ' + position;
      var enrichedError = new Error(errorText);
      enrichedError.lineNumber = lineNumber;
      enrichedError.position = position;
      throw enrichedError;
    }
    throw new Error(METADATA_ERROR_PREFIX + ': ' + message);
  }

  var startIndex = rawFragmentShader.indexOf('/*');
  var endIndex = rawFragmentShader.indexOf('*/');
  return {
    objectValue: metadata,
    stringValue: metadataString,
    startIndex: startIndex,
    endIndex: endIndex
  };
};