'use strict';

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

var _isNan = require('babel-runtime/core-js/number/is-nan');

var _isNan2 = _interopRequireDefault(_isNan);

var _keys = require('babel-runtime/core-js/object/keys');

var _keys2 = _interopRequireDefault(_keys);

var _stringify = require('babel-runtime/core-js/json/stringify');

var _stringify2 = _interopRequireDefault(_stringify);

var _assign = require('babel-runtime/core-js/object/assign');

var _assign2 = _interopRequireDefault(_assign);

var _getPrototypeOf = require('babel-runtime/core-js/object/get-prototype-of');

var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);

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 _react = require('react');

var _react2 = _interopRequireDefault(_react);

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

var _propTypes2 = _interopRequireDefault(_propTypes);

var _IconButton = require('@material-ui/core/IconButton');

var _IconButton2 = _interopRequireDefault(_IconButton);

var _Tooltip = require('@material-ui/core/Tooltip');

var _Tooltip2 = _interopRequireDefault(_Tooltip);

var _MoreVert = require('@material-ui/icons/MoreVert');

var _MoreVert2 = _interopRequireDefault(_MoreVert);

var _featureFilterGeojson = require('feature-filter-geojson');

var _featureFilterGeojson2 = _interopRequireDefault(_featureFilterGeojson);

var _Menu = require('@material-ui/core/Menu');

var _Menu2 = _interopRequireDefault(_Menu);

var _MenuItem = require('@material-ui/core/MenuItem');

var _MenuItem2 = _interopRequireDefault(_MenuItem);

var _reactIntl = require('react-intl');

var _fileSaver = require('file-saver');

var _d3Dsv = require('d3-dsv');

var _objectAssign = require('object-assign');

var _objectAssign2 = _interopRequireDefault(_objectAssign);

var _moment = require('moment');

var _moment2 = _interopRequireDefault(_moment);

var _formatLocation = require('../../util/formatLocation');

var _formatLocation2 = _interopRequireDefault(_formatLocation);

var _flat = require('../../util/flat');

var _prop_types = require('../../util/prop_types');

var MFPropTypes = _interopRequireWildcard(_prop_types);

var _ViewContainer = require('../../containers/ViewContainer');

var _ViewContainer2 = _interopRequireDefault(_ViewContainer);

var _constants = require('../../constants');

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }

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

var messages = (0, _reactIntl.defineMessages)({
  settings: {
    'id': 'menu.settings',
    'defaultMessage': 'Settings'
  },
  menu: {
    'id': 'buttons.menu',
    'defaultMessage': 'Menu'
  },
  exportGeoJSON: {
    'id': 'menu.exportGeoJSON',
    'defaultMessage': 'Export GeoJSON\u2026'
  },
  exportCSV: {
    'id': 'menu.exportCSV',
    'defaultMessage': 'Export CSV\u2026'
  }
});

var MenuButton = function (_React$Component) {
  (0, _inherits3.default)(MenuButton, _React$Component);

  function MenuButton() {
    var _ref;

    var _temp, _this, _ret;

    (0, _classCallCheck3.default)(this, MenuButton);

    for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    return _ret = (_temp = (_this = (0, _possibleConstructorReturn3.default)(this, (_ref = MenuButton.__proto__ || (0, _getPrototypeOf2.default)(MenuButton)).call.apply(_ref, [this].concat(args))), _this), _this.state = { open: false }, _this.handleClick = function (event) {
      _this.setState({ open: true, anchorEl: event.currentTarget });
    }, _this.handleRequestClose = function () {
      _this.setState({ open: false });
    }, _this.handleExportGeoJSONClick = function () {
      var ff = (0, _featureFilterGeojson2.default)(_this.props.filter);
      var features = _this.props.features.filter(ff).map(function (f) {
        var newProps = {};
        for (var prop in f.properties) {
          newProps[prop] = _this._convertValue(prop, f.properties[prop]);
        }
        return (0, _assign2.default)({}, f, { properties: (0, _flat.unflatten)(newProps) });
      });
      var geojson = {
        type: 'FeatureCollection',
        features: features
      };
      var blob = new window.Blob([(0, _stringify2.default)(geojson, null, 2)], { type: 'application/json' });
      (0, _fileSaver.saveAs)(blob, 'data.geojson');
    }, _this.handleExportCSVClick = function () {
      var columns = [];
      var ff = (0, _featureFilterGeojson2.default)(_this.props.filter);
      var rows = _this.props.features.filter(ff).map(function (feature) {
        var row = (0, _assign2.default)({}, feature.properties);
        (0, _keys2.default)(row).forEach(function (key) {
          row[key] = _this._convertValue(key, row[key]);
          if (columns.indexOf(key) === -1) columns.push(key);
        });
        if (feature.geometry && feature.geometry.type === 'Point') {
          var coords = feature.geometry.coordinates;
          return (0, _objectAssign2.default)({}, row, {
            lon: coords[0],
            lat: coords[1],
            UTM: (0, _formatLocation2.default)(coords, _constants.FORMATS_UTM)
          });
        }
        return row;
      }).filter(Boolean);
      var csv = (0, _d3Dsv.csvFormat)(rows, columns.sort().concat(['UTM', 'lon', 'lat']));
      var blob = new window.Blob([csv], { type: 'text/csv' });
      (0, _fileSaver.saveAs)(blob, 'data.csv');
    }, _temp), (0, _possibleConstructorReturn3.default)(_this, _ret);
  }

  (0, _createClass3.default)(MenuButton, [{
    key: '_convertValue',
    value: function _convertValue(prop, value) {
      var fieldAnalysis = this.props.fieldAnalysis;

      if (fieldAnalysis.properties[prop] && fieldAnalysis.properties[prop].type === _constants.FIELD_TYPE_DATE) {
        if (typeof value === 'number' && !(0, _isNan2.default)(value)) {
          return (0, _moment2.default)(value).format('YYYY-MM-DD HH:mm:ss');
        } else {
          return '';
        }
      }
      if (value === _constants.UNDEFINED_KEY) return '';
      return value;
    }
  }, {
    key: 'render',
    value: function render() {
      var _props = this.props,
          formatMessage = _props.intl.formatMessage,
          openSettings = _props.openSettings,
          menuItems = _props.menuItems;

      var name = formatMessage(messages.menu);
      return _react2.default.createElement(
        'div',
        null,
        _react2.default.createElement(
          _Tooltip2.default,
          { title: name },
          _react2.default.createElement(
            _IconButton2.default,
            {
              'aria-owns': this.state.open ? 'toolbar-menu' : null,
              'aria-haspopup': 'true',
              onClick: this.handleClick,
              'aria-label': name },
            _react2.default.createElement(_MoreVert2.default, { nativeColor: 'white' })
          )
        ),
        _react2.default.createElement(
          _Menu2.default,
          {
            open: this.state.open,
            MenuListProps: { dense: true },
            id: 'toolbar-menu',
            anchorEl: this.state.anchorEl,
            onClick: this.handleRequestClose,
            onClose: this.handleRequestClose },
          _react2.default.createElement(
            _MenuItem2.default,
            { onClick: function onClick() {
                return openSettings('general');
              } },
            formatMessage(messages.settings)
          ),
          _react2.default.createElement(
            _MenuItem2.default,
            { onClick: this.handleExportGeoJSONClick },
            formatMessage(messages.exportGeoJSON)
          ),
          _react2.default.createElement(
            _MenuItem2.default,
            { onClick: this.handleExportCSVClick },
            formatMessage(messages.exportCSV)
          ),
          menuItems.length === 0 ? null : menuItems.map(function (menuItem, i) {
            return _react2.default.createElement(_ViewContainer2.default, { key: i, component: menuItem });
          })
        )
      );
    }
  }]);
  return MenuButton;
}(_react2.default.Component);

MenuButton.defaultProps = {
  menuItems: []
};

MenuButton.propTypes = {
  features: MFPropTypes.features,
  intl: _propTypes2.default.object.isRequired,
  openSettings: _propTypes2.default.func.isRequired
};

exports.default = (0, _reactIntl.injectIntl)(MenuButton);
//# sourceMappingURL=MenuButton.js.map