/*eslint no-unused-vars: [2, { "args": "none" }]*/
'use strict';

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

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _get = function get(object, property, receiver) { 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 { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };

var _lodash = require('lodash');

var _lodash2 = _interopRequireDefault(_lodash);

var _classnames = require('classnames');

var _classnames2 = _interopRequireDefault(_classnames);

var _Common = {
  "inner-block": "Common__inner-block___2cOrF",
  "disable-inner-block": "Common__disable-inner-block___1MLd0",
  "components": "Common__components___2fQuj",
  "component": "Common__component___3bwMg",
  "hide": "Common__hide___2HyoH",
  "desc-text-color": "Common__desc-text-color___2fV3l",
  "desc-text-block": "Common__desc-text-block___1Z4b-",
  "text-link": "Common__text-link___1jaLy",
  "image": "Common__image___AKB6W",
  "imagediff": "Common__imagediff___2j7tX",
  "slideshow": "Common__slideshow___1Fz23",
  "embeddedcode": "Common__embeddedcode___3Avmp",
  "youtube": "Common__youtube___2oq1n",
  "topic-box": "Common__topic-box___2Q-kN"
};

var _Common2 = _interopRequireDefault(_Common);

var _FitwidthMixin2 = require('./mixins/FitwidthMixin');

var _FitwidthMixin3 = _interopRequireDefault(_FitwidthMixin2);

var _index = require('../../utils/index');

var _BlockAlignmentWrapper = require('./BlockAlignmentWrapper');

var _BlockAlignmentWrapper2 = _interopRequireDefault(_BlockAlignmentWrapper);

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _reactDom = require('react-dom');

var _reactDom2 = _interopRequireDefault(_reactDom);

var _reactLazyLoad = require('react-lazy-load');

var _reactLazyLoad2 = _interopRequireDefault(_reactLazyLoad);

var _Image = {
  "image-box": "Image__image-box___1DLHm",
  "img-absolute": "Image__img-absolute___1PZNy",
  "img-placeholder-outer": "Image__img-placeholder-outer___XtT0Y",
  "img-placeholder": "Image__img-placeholder___h0DPn",
  "img-description": "Image__img-description___27Qc1"
};

var _Image2 = _interopRequireDefault(_Image);

var _uiSettings = require('../../constants/ui-settings');

var _uiSettings2 = _interopRequireDefault(_uiSettings);

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 _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

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 DEFAULT_WIDTH = 200;
var DEFAULT_HEIGHT = 200;

var Image = function (_FitwidthMixin) {
  _inherits(Image, _FitwidthMixin);

  function Image(props) {
    _classCallCheck(this, Image);

    var _this = _possibleConstructorReturn(this, (Image.__proto__ || Object.getPrototypeOf(Image)).call(this, props));

    _this.state = {
      isMounted: false,
      screenType: 'MOBILE',
      width: DEFAULT_WIDTH,
      placeholderOpacity: 0,
      imageOpacity: 0
    };

    _this.fitToParentWidth = _this.fitToParentWidth.bind(_this);
    return _this;
  }

  _createClass(Image, [{
    key: 'componentDidMount',
    value: function componentDidMount() {
      this.setState({
        isMounted: true,
        screenType: (0, _index.getScreenType)(window.innerWidth)
      });

      if (_get(Image.prototype.__proto__ || Object.getPrototypeOf(Image.prototype), 'componentDidMount', this)) _get(Image.prototype.__proto__ || Object.getPrototypeOf(Image.prototype), 'componentDidMount', this).call(this);
    }
  }, {
    key: 'componentWillReceiveProps',
    value: function componentWillReceiveProps(nextProps) {
      if (_reactDom2.default.findDOMNode(this)) {
        this.fitToParentWidth();
      }
    }
  }, {
    key: '_renderPlaceHoderImage',
    value: function _renderPlaceHoderImage(imageUrl, imgStyle) {
      var _this2 = this;

      if (imageUrl) {
        return _react2.default.createElement(
          _reactLazyLoad2.default,
          { offsetTop: _uiSettings2.default.image.loadingOffset.placeholder,
            onContentVisible: function onContentVisible() {
              return _this2.setState({ placeholderOpacity: 1 });
            },
            className: _Image2.default['img-placeholder-outer'],
            style: _extends({}, imgStyle, { opacity: this.state.placeholderOpacity }) },
          _react2.default.createElement('img', { src: imageUrl, className: (0, _classnames2.default)('center-block', _Image2.default['img-placeholder']), style: imgStyle })
        );
      }
      return null;
    }
  }, {
    key: '_renderFigure',
    value: function _renderFigure(imageObj, imgStyle) {
      var _this3 = this;

      if (_lodash2.default.get(imageObj, 'url')) {
        return _react2.default.createElement(
          'figure',
          null,
          _react2.default.createElement(
            _reactLazyLoad2.default,
            { offsetTop: _uiSettings2.default.image.loadingOffset.image, onContentVisible: function onContentVisible() {
                return _this3.setState({ imageOpacity: 1 });
              } },
            _react2.default.createElement('img', { src: imageObj.url,
              style: _extends({}, imgStyle, { opacity: this.state.imageOpacity }),
              className: (0, _classnames2.default)('center-block', _Image2.default['img-absolute'])
            })
          )
        );
      }
      return null;
    }
  }, {
    key: '_getNoscript',
    value: function _getNoscript(imgUrl, imgDes) {
      // generate image tag for search engines
      return {
        __html: '<img src="' + imgUrl + '" alt="' + imgDes + '">'
      };
    }
  }, {
    key: 'render',
    value: function render() {
      var imageByDevice = _lodash2.default.get(this.props, ['content', 0], {});
      if (imageByDevice === null) {
        return null;
      }
      var desktop = imageByDevice.desktop;
      var tiny = imageByDevice.tiny;
      var _state = this.state;
      var isMounted = _state.isMounted;
      var screenType = _state.screenType;
      var width = _state.width;
      var _props = this.props;
      var isToShowDescription = _props.isToShowDescription;
      var outerWidth = _props.outerWidth;
      var outerHeight = _props.outerHeight;

      var boxWidth = outerWidth || width;
      var boxHeight = outerHeight || this._getHeight(boxWidth, desktop, DEFAULT_WIDTH, DEFAULT_HEIGHT);
      var renderedPlaceHoderImage = null;
      var renderedFigure = null;
      var imageDescription = _lodash2.default.get(imageByDevice, 'description', null);
      var descriptionBox = void 0;

      var outerStyle = {
        width: boxWidth,
        minHeight: boxHeight
      };
      var imgStyle = _extends({}, outerStyle, {
        height: boxHeight
      });

      // if the Image is being mounted, select image to render
      // according to the device of the client
      if (isMounted) {
        renderedPlaceHoderImage = this._renderPlaceHoderImage(_lodash2.default.get(tiny, ['url']), imgStyle);
        renderedFigure = this._renderByDevice(screenType, imageByDevice, imgStyle);
      }

      if (imageDescription && isToShowDescription) {
        descriptionBox = _react2.default.createElement(
          'div',
          {
            className: (0, _classnames2.default)(_Common2.default['desc-text-block'], 'text-justify'),
            style: { marginTop: '16px' }
          },
          imageDescription
        );
      }

      return _react2.default.createElement(
        'div',
        { ref: 'imageBox', className: _Image2.default['image-box'] },
        _react2.default.createElement(
          'div',
          { style: outerStyle },
          renderedPlaceHoderImage,
          renderedFigure,
          _react2.default.createElement('noscript', { dangerouslySetInnerHTML: this._getNoscript(_lodash2.default.get(desktop, 'url', ''), imageDescription) })
        ),
        descriptionBox
      );
    }
  }]);

  return Image;
}((0, _FitwidthMixin3.default)(_react.Component));

Image.propTypes = {
  content: _react2.default.PropTypes.array,
  customeStyles: _react2.default.PropTypes.array,
  isToShowDescription: _react2.default.PropTypes.bool,
  outerHeight: _react2.default.PropTypes.number,
  outerWidth: _react2.default.PropTypes.number
};

Image.defaultProps = {
  content: [],
  customeStyles: [],
  isToShowDescription: true,
  outerHeight: 0,
  outerWidth: 0
};

var AlignedImage = (0, _BlockAlignmentWrapper2.default)(Image);

exports.AlignedImage = AlignedImage;
exports.Image = Image;