'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.SDKApp = exports.generateFormats = undefined;

var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = require('babel-runtime/helpers/createClass');

var _createClass3 = _interopRequireDefault(_createClass2);

var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn');

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _inherits2 = require('babel-runtime/helpers/inherits');

var _inherits3 = _interopRequireDefault(_inherits2);

var _dec, _class, _class2, _temp; /* eslint "import/no-extraneous-dependencies": "warn" */
/* eslint "import/no-webpack-loader-syntax": "warn" */
/* eslint "import/no-unresolved": "warn" */


var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _propTypes = require('prop-types');

var _propTypes2 = _interopRequireDefault(_propTypes);

var _reactDndHtml5Backend = require('react-dnd-html5-backend');

var _reactDndHtml5Backend2 = _interopRequireDefault(_reactDndHtml5Backend);

var _reactDnd = require('react-dnd');

require('style-loader!css-loader!normalize.css/normalize.css');

var _lib = require('@instructure/ui-themeable/lib');

var _lib2 = _interopRequireDefault(_lib);

var _Locale = require('@instructure/ui-i18n/lib/Locale');

var _Locale2 = _interopRequireDefault(_Locale);

var _ApplyLocale = require('@instructure/ui-i18n/lib/components/ApplyLocale');

var _ApplyLocale2 = _interopRequireDefault(_ApplyLocale);

var _formatMessage = require('quiz-interactions/lib/format-message');

var _formatMessage2 = _interopRequireDefault(_formatMessage);

var _reactRedux = require('../../react-redux');

var _reduxStore = require('../../../reduxStore');

var _reduxStore2 = _interopRequireDefault(_reduxStore);

var _formatMessage3 = require('../../format-message');

var _formatMessage4 = _interopRequireDefault(_formatMessage3);

var _features = require('../../api/features');

var _ui = require('../../actions/ui');

var _config = require('../../actions/config');

var _outcomes = require('../../actions/outcomes');

var _features2 = require('../../actions/features');

var _renderAlerts = require('../../util/renderAlerts');

var _renderAlerts2 = _interopRequireDefault(_renderAlerts);

var _theme = require('./theme');

var _theme2 = _interopRequireDefault(_theme);

var _CustomPropTypes = require('../../../common/util/CustomPropTypes');

var _CustomPropTypes2 = _interopRequireDefault(_CustomPropTypes);

var _ConfirmationModal = require('../ConfirmationModal');

var _ConfirmationModal2 = _interopRequireDefault(_ConfirmationModal);

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

var styles = {
  template: function template(theme) {
    return '/*\n  imported from styles.css \n */\n\n.SDKApp__styles__sdk {\n  height: 100%;\n}\n\n/*\n * The normalize.css reset sets -webkit-appearance to button here:\n * https://github.com/necolas/normalize.css/blob/4.2.0/normalize.css#L302-L307.\n *\n * This overrides this change to fix styling issues in consumer apps.\n *\n * TODO: remove normalize.css, then remove this\n */\nhtml [type="button"] {\n    /* stylelint-disable property-no-vendor-prefix */\n    -webkit-appearance: inherit;\n    /* stylelint-enable property-no-vendor-prefix */\n  }\n';
  },
  'sdk': 'SDKApp__styles__sdk'
};


/**
 * Generate custom formats for format-message.
 * NOTE: We should NOT override any of the defaults here:
 * https://github.com/format-message/format-message/tree/master/packages/message-format
 *
 * As that can cause problems when this library is consumed.
 * @param {string} timeZone
 */
var generateFormats = exports.generateFormats = function generateFormats(timeZone) {
  return {
    number: {
      decimal_2_min_integer_no_fraction: {
        style: 'decimal',
        maximumFractionDigits: 0,
        minimumIntegerDigits: 2
      },
      decimal_2_fraction_digits: {
        style: 'decimal',
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
      }
    },
    date: {
      datetime_long: {
        weekday: 'long',
        year: 'numeric',
        month: 'long',
        day: 'numeric',
        hour: 'numeric',
        minute: 'numeric',
        timeZone: timeZone
      },
      datetime_medium: {
        year: 'numeric',
        month: 'short',
        day: 'numeric',
        hour: 'numeric',
        minute: 'numeric',
        timeZone: timeZone
      },
      default: {
        timeZone: timeZone
      }
    },
    time: {
      hour_minute: {
        hour: 'numeric',
        minute: 'numeric',
        timeZone: timeZone
      }
    }
  };
};

var SDKApp = exports.SDKApp = (_dec = (0, _lib2.default)(_theme2.default, styles), _dec(_class = (_temp = _class2 = function (_Component) {
  (0, _inherits3.default)(SDKApp, _Component);

  function SDKApp(props) {
    (0, _classCallCheck3.default)(this, SDKApp);

    // TODO: move to something like this down the line
    // so we dont implicitly share state
    // this.store = this.configureStore()
    var _this = (0, _possibleConstructorReturn3.default)(this, (SDKApp.__proto__ || Object.getPrototypeOf(SDKApp)).call(this, props));

    _this.store = _reduxStore2.default;
    _this.setLocale();
    return _this;
  }

  (0, _createClass3.default)(SDKApp, [{
    key: 'setLocale',
    value: function setLocale() {
      var locale = this.props.locale;
      var timeZone = this.props.timeZone;

      /* All the Etc/GMT± timezones will succeed if they are the browser default, but
       * if we pass in the browser default as a string (as in timeZone's defaultProps)
       * then it doesn't pass the validation regex. So we will need to remap these to
       * timezones that have the same offset
       */

      var tzMapping = {
        'Etc/GMT+5': 'America/Cayman', // this one isn't strictly necessary, here for example
        'Etc/GMT+7': 'America/Phoenix'
      };
      if (timeZone in tzMapping) {
        timeZone = tzMapping[timeZone];
      }

      try {
        // see if the browser will accept the given timezone
        Intl.DateTimeFormat('en', { timeZone: timeZone });
      } catch (err) {
        // UTC is the only value all browsers must recognize
        timeZone = 'UTC';
      }

      _formatMessage4.default.setup({
        formats: generateFormats(timeZone),
        missingTranslation: 'ignore',
        locale: locale
      });
      _formatMessage2.default.setup({ locale: locale });
    }
  }, {
    key: 'setAppContainer',
    value: function setAppContainer(appContainer) {
      var selectors = Array.isArray(appContainer) ? appContainer : [appContainer];
      return (0, _ui.set)('appContainer', selectors);
    }
  }, {
    key: 'componentWillMount',
    value: function componentWillMount() {
      this.store.dispatch([(0, _config.setAPIEndpoint)(this.props.apiEndpoint), this.setAppContainer(this.props.appContainer), (0, _config.setUserToken)(this.props.userToken), (0, _outcomes.setOutcomesEndpoint)(this.props.outcomesEndpoint), (0, _outcomes.setOutcomesToken)(this.props.outcomesToken), (0, _outcomes.setContextUuid)(this.props.contextUuid)]);
      this.store.dispatch((0, _features.getFeatures)());
      if (this.props.itemBankSharingEnabled) {
        this.store.dispatch((0, _features2.addFeatures)('item_bank_sharing'));
      }
    }
  }, {
    key: 'componentDidMount',
    value: function componentDidMount() {
      // inserts the a11y friendly alerts
      // react app hooked up to the store
      (0, _renderAlerts2.default)(this.store);
    }
  }, {
    key: 'componentWillReceiveProps',
    value: function componentWillReceiveProps(newProps) {
      if (newProps.apiEndpoint !== this.props.apiEndpoint) {
        this.store.dispatch((0, _config.setAPIEndpoint)(newProps.apiEndpoint));
      }
      if (newProps.appContainer !== this.props.appContainer) {
        this.store.dispatch(this.setAppContainer(newProps.appContainer));
      }
      if (newProps.userToken !== this.props.userToken) {
        this.store.dispatch((0, _config.setUserToken)(newProps.userToken));
      }
      if (newProps.outcomesEndpoint !== this.props.outcomesEndpoint) {
        this.store.dispatch((0, _outcomes.setOutcomesEndpoint)(newProps.outcomesEndpoint));
      }
      if (newProps.outcomesToken !== this.props.outcomesToken) {
        this.store.dispatch((0, _outcomes.setOutcomesToken)(newProps.outcomesToken));
      }
      if (newProps.contextUuid !== this.props.contextUuid) {
        this.store.dispatch((0, _outcomes.setContextUuid)(newProps.contextUuid));
      }
      if (newProps.itemBankSharingEnabled !== this.props.itemBankSharingEnabled) {
        var toggleFeature = newProps.itemBankSharingEnabled ? _features2.addFeatures : _features2.removeFeatures;
        this.store.dispatch(toggleFeature('item_bank_sharing'));
      }
    }
  }, {
    key: 'render',
    value: function render() {
      var store = this.store,
          _props = this.props,
          children = _props.children,
          locale = _props.locale,
          timeZone = _props.timeZone;


      return _react2.default.createElement(
        _reactRedux.Provider,
        { store: store },
        _react2.default.createElement(
          _ApplyLocale2.default,
          { locale: locale, timezone: timeZone },
          _react2.default.createElement(
            'div',
            { className: styles.sdk, 'data-automation': 'sdk-app' },
            _react2.default.createElement(_ConfirmationModal2.default, null),
            children
          )
        )
      );
    }
  }]);
  SDKApp.displayName = 'SDKApp'
  ;
  return SDKApp;
}(_react.Component), _class2.propTypes = {
  apiEndpoint: _propTypes2.default.string.isRequired,
  appContainer: _CustomPropTypes2.default.selectors.isRequired,
  children: _propTypes2.default.node.isRequired,
  contextUuid: _propTypes2.default.string,
  itemBankSharingEnabled: _propTypes2.default.bool,
  locale: _propTypes2.default.string,
  outcomesEndpoint: _propTypes2.default.string,
  outcomesToken: _propTypes2.default.string,
  timeZone: _propTypes2.default.string,
  userToken: _propTypes2.default.string.isRequired
}, _class2.defaultProps = {
  contextUuid: null,
  itemBankSharingEnabled: false,
  locale: _Locale2.default.browserLocale(),
  outcomesEndpoint: null,
  outcomesToken: null,
  timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone
}, _temp)) || _class);


var DragDroppableSDKApp = (0, _reactDnd.DragDropContext)(_reactDndHtml5Backend2.default)(SDKApp);

exports.default = DragDroppableSDKApp;