/**
 * Copyright 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */
/*global exports:true*/

var Syntax = require('esprima-fb').Syntax;
var utils = require('../src/utils');
var reserverdWordsHelper = require('./reserved-words-helper');

/**
 * Code adapted from https://github.com/spicyj/es3ify
 * The MIT License (MIT)
 * Copyright (c) 2014 Ben Alpert
 */

function visitProperty(traverse, node, path, state) {
  utils.catchup(node.key.range[0], state);
  utils.append('"', state);
  utils.catchup(node.key.range[1], state);
  utils.append('"', state);
  utils.catchup(node.value.range[0], state);
  traverse(node.value, path, state);
  return false;
}

visitProperty.test = function(node) {
  return node.type === Syntax.Property &&
    node.key.type === Syntax.Identifier &&
    !node.method &&
    !node.shorthand &&
    !node.computed &&
    reserverdWordsHelper.isES3ReservedWord(node.key.name);
};

function visitMemberExpression(traverse, node, path, state) {
  traverse(node.object, path, state);
  // Member expression range does not include parenthesis, so simply specifying
  // node.object.range[1] as the start position doesn't work. Neither does
  // node.property.range[0] - 1 as that won't catch expressions that span
  // newlines (period on previous line). So instead we'll catchup and remove
  // any periods.
  utils.catchup(node.property.range[0], state, function(s) {
    return s.replace('.', '');
  });
  utils.append('[', state);
  utils.catchupWhiteSpace(node.property.range[0], state);
  utils.append('"', state);
  utils.catchup(node.property.range[1], state);
  utils.append('"]', state);
  return false;
}

visitMemberExpression.test = function(node) {
  return node.type === Syntax.MemberExpression &&
    node.property.type === Syntax.Identifier &&
    reserverdWordsHelper.isES3ReservedWord(node.property.name);
};

exports.visitorList = [
  visitProperty,
  visitMemberExpression
];
