// Copied and modified from https://gist.github.com/walter/3e852e8ebc87535a3c91
import Ember from 'ember';
import config from 'bo-client/config/environment';


export function initialize(application) {
  var OptionsReader = function OptionsReader() {
    this.readOptionsKeys = function() {
      var _mapType = function(val) {
        return "" === val ? null : "true" === val ? true : "false" === val ? false : (-1 !== val.indexOf(",") && (val = val.split(",")), val);
      };

      // Grab all the meta tags from the DOM.
      var metaTags = Ember.$("meta");
      var options = Ember.Object.create();
      var re = new RegExp(config.modulePrefix + '\.');

      // Process each of the discovered meta tags.
      for(var i=0; i < metaTags.length; i++) {
        var key = Ember.$(metaTags[i]).attr('name');
        var value = Ember.$(metaTags[i]).attr('content');

        // Does the meta tag start with our MODULE_PREFIX?
        if (re.test(key)) {
          var propertyName = Ember.String.camelize(key.substring(config.modulePrefix.length+1));
          options[propertyName] = _mapType(value);
        }
      }
      return options;
    };
  };

  var optionsReader = new OptionsReader();

  application.register('service:options', optionsReader.readOptionsKeys(), {singleton: true, instantiate: false});

}

export default {
  name: 'options',
  initialize
};
