'use strict';

Object.defineProperty(exports, '__esModule', {
  value: true
});

var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };

exports['default'] = RitzyFactory;

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }

function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var _reactAddons = require('react/addons');

var _reactAddons2 = _interopRequireDefault(_reactAddons);

var _webfontloader = require('webfontloader');

var _webfontloader2 = _interopRequireDefault(_webfontloader);

var _opentypeJs = require('opentype.js');

var _opentypeJs2 = _interopRequireDefault(_opentypeJs);

var _componentsEditor = require('./components/Editor');

var _componentsEditor2 = _interopRequireDefault(_componentsEditor);

var _coreDom = require('./core/dom');

var renderEditor = function renderEditor(config, renderTarget) {
  var configDefault = function configDefault(key, defaultValue) {
    if (!config[key]) {
      if (typeof defaultValue === 'function') {
        config[key] = defaultValue();
      } else {
        config[key] = defaultValue;
      }
    }
  };

  var configRequire = function configRequire(key) {
    if (!config[key]) {
      throw new Error('Configuration must contain a property \'' + key + '\'.');
    }
  };

  configRequire('id');
  configRequire('fonts');
  configDefault('fontSize', 18);
  configRequire('minFontSize');
  configRequire('unitsPerEm');
  configDefault('width', 600);
  configDefault('marginH', 30);
  configDefault('marginV', 35);
  configDefault('userId', function () {
    var localUser = window.localStorage.getItem('localuser') || 'A' + parseInt(Math.random() * 10000).toString(16);
    window.localStorage.setItem('localuser', localUser);
    return localUser;
  });
  configDefault('userName', config.userId);

  var editorFactory = _reactAddons2['default'].createFactory(_componentsEditor2['default']);

  _reactAddons2['default'].render(editorFactory(config), renderTarget);
};

var webFontPromise = function webFontPromise(webFontFamily) {
  return new Promise(function (resolve, reject) {
    var webFontConfig = {
      classes: false,
      active: function active() {
        resolve();
      },
      inactive: function inactive() {
        reject(Error('Webfonts [' + JSON.stringify(webFontFamily) + '] could not be loaded.'));
      }
    };
    Object.keys(webFontFamily).forEach(function (k) {
      return webFontConfig[k] = webFontFamily[k];
    });
    _webfontloader2['default'].load(webFontConfig);
  });
};

var otFontPromise = function otFontPromise(fontUrl) {
  return new Promise(function (resolve, reject) {
    _opentypeJs2['default'].load(fontUrl, function (err, font) {
      if (err) {
        reject(Error('Opentype.js font ' + fontUrl + ' could not be loaded: ' + err));
      } else {
        resolve(font);
      }
    });
  });
};

function render(config, renderTarget) {
  var configDefault = function configDefault(key, defaultValue) {
    if (!config[key]) {
      config[key] = defaultValue;
    }
  };

  // if config.skin is undefined or 'default', we load default-skin.less
  configDefault('skin', 'default');
  if (config.skin === 'default') {
    require('./styles/default-skin.less');
  }

  configDefault('localFontPath', '/fonts/');
  configDefault('fontRegular', 'OpenSans-Regular-Latin.ttf');
  configDefault('fontBold', 'OpenSans-Bold-Latin.ttf');
  configDefault('fontBoldItalic', 'OpenSans-BoldItalic-Latin.ttf');
  configDefault('fontItalic', 'OpenSans-Italic-Latin.ttf');
  configDefault('webFontFamily', {
    google: {
      families: ['Open Sans:400italic,700italic,700,400']
    }
  });

  //noinspection JSUnresolvedVariable
  Promise.all([otFontPromise(config.localFontPath + config.fontRegular), otFontPromise(config.localFontPath + config.fontBold), otFontPromise(config.localFontPath + config.fontBoldItalic), otFontPromise(config.localFontPath + config.fontItalic), webFontPromise(config.webFontFamily)]).then(function (fontsResult) {
    config.fonts = {
      regular: fontsResult[0],
      bold: fontsResult[1],
      boldItalic: fontsResult[2],
      italic: fontsResult[3]
    };

    // all units per em must be the same (they are for OpenSans)
    config.unitsPerEm = fontsResult[0].unitsPerEm;

    // we could detect minFontSize when needed (with this one-time approach, if the user changes it, they will need to refresh)
    config.minFontSize = (0, _coreDom.detectMinFontSize)();

    renderEditor(config, renderTarget);
  })['catch'](function (err) {
    console.error('Editor loading failed.', err);
    if (typeof config.onLoadError === 'function') {
      config.onLoadError(err);
    }
  });
}

function RitzyFactory(config, eventEmitter) {
  var EventEmitter = eventEmitter ? eventEmitter : require('eventemitter3');

  var Ritzy = (function (_EventEmitter) {
    _inherits(Ritzy, _EventEmitter);

    function Ritzy(c) {
      _classCallCheck(this, Ritzy);

      _get(Object.getPrototypeOf(Ritzy.prototype), 'constructor', this).call(this);
      this.render = function (renderTarget) {
        render(c, renderTarget);
      };
    }

    return Ritzy;
  })(EventEmitter);

  return new Ritzy(config);
}

module.exports = exports['default'];