// Copyright 2012 YDN Authors. All Rights Reserved.
//
// 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.

/**
 * @fileoverview Robust JSON wrapper.
 */

goog.provide('ydn.json');
goog.require('goog.debug.Logger');
goog.require('goog.json');


/**
 *
 * @define {boolean} enable debug to log erronous object.
 */
ydn.json.DEBUG = false;


/**
 * @final
 * @type {goog.debug.Logger}
 */
ydn.json.logger = goog.debug.Logger.getLogger('ydn');


/**
 * @const
 * @type {boolean} indicate native JSON paraser is available.
 */
ydn.json.native = !(typeof goog.global['JSON'] == 'undefined');


/**
 * Parse JSON using native method if available.
 * This is necessary since closure-library do not use native method.
 *
 * @param {*} json_str string to parse.
 * @return {!Object} parse return object.
 */
ydn.json.parse = function(json_str) {
  if (!goog.isString(json_str) || goog.string.isEmpty(json_str)) {
    return {};
  }
  if (ydn.json.native) {
    return /** @type {!Object} */ (JSON.parse(json_str));
  } else {
    return /** @type {!Object} */ (goog.json.parse(json_str));
  }
};


/**
 * Note: This is mainly used in debugging.
 * @param obj
 * @return {string}
 */
ydn.json.toShortString = function(obj) {
  var json;
  /** @preserveTry */
  try {
    json = ydn.json.stringify(obj);
  } catch (e) {
    json = '';
  }
  if (json) {
    return json.substr(0, 70) + (json.length > 70 ? '...' : '');
  } else {
    return '';
  }

};


/**
 * Parse JSON using native method if available.
 *
 * This is necessary since closure-library do not use native method.
 *
 * @param {Object} json object to stringify.
 * @return {string} result.
 */
ydn.json.stringify = function(json) {

  if (ydn.json.native) {
    return JSON.stringify(json);
  } else {
    return goog.json.serialize(json);
  }
};

@@ -833,24 +833,102 @@
  = false;%0A%0A%0A
+/**%0A * @define %7Bboolean%7D Use JSON polyfill.%0A */%0Aydn.json.POLY_FILL = false;%0A%0A%0A
 /**%0A * @fina
@@ -1115,16 +1115,49 @@
 native =
+ !ydn.json.POLY_FILL ? true :%0A   
  !(typeo

add json polyfill as optional flag.