'use strict';

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

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 _yogaLayout = require('yoga-layout');

var _yogaLayout2 = _interopRequireDefault(_yogaLayout);

var _Base2 = require('./Base');

var _Base3 = _interopRequireDefault(_Base2);

var _image = require('../utils/image');

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

function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; }

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 SAFETY_HEIGHT = 10;

// We manage two bounding boxes in this class:
//  - Yoga node: Image bounding box. Adjust based on image and page size
//  - Image node: Real image container. In most cases equals Yoga node, except if image is bigger than page

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

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

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

    _this.image = null;
    _this.layout.setMeasureFunc(_this.measureImage.bind(_this));
    return _this;
  }

  _createClass(Image, [{
    key: 'shouldGrow',
    value: function shouldGrow() {
      return !!this.getComputedStyles().flexGrow;
    }
  }, {
    key: 'measureImage',
    value: function measureImage(width, widthMode, height, heightMode) {
      var imageMargin = this.margin;
      var pagePadding = this.page.padding;

      var pageArea = this.page.height - pagePadding.top - pagePadding.bottom - imageMargin.top - imageMargin.bottom - SAFETY_HEIGHT;

      if (widthMode === _yogaLayout2.default.MEASURE_MODE_EXACTLY && heightMode === _yogaLayout2.default.MEASURE_MODE_UNDEFINED) {
        var scaledHeight = width / this.ratio;
        return { height: Math.min(pageArea, scaledHeight) };
      }

      if (heightMode === _yogaLayout2.default.MEASURE_MODE_EXACTLY && widthMode === _yogaLayout2.default.MEASURE_MODE_UNDEFINED) {
        return { width: height * this.ratio };
      }

      if (widthMode === _yogaLayout2.default.MEASURE_MODE_EXACTLY && heightMode === _yogaLayout2.default.MEASURE_MODE_AT_MOST) {
        var _scaledHeight = width / this.ratio;
        return { height: Math.min(height, pageArea, _scaledHeight) };
      }

      if (widthMode === _yogaLayout2.default.MEASURE_MODE_AT_MOST && heightMode === _yogaLayout2.default.MEASURE_MODE_AT_MOST) {
        var imageWidth = Math.min(this.image.width, width);

        return {
          width: imageWidth,
          height: this.calculateHeight(imageWidth)
        };
      }

      return { height: height, width: width };
    }
  }, {
    key: 'isEmpty',
    value: function isEmpty() {
      return false;
    }
  }, {
    key: 'fetch',
    value: function () {
      var _ref = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() {
        return regeneratorRuntime.wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                _context.prev = 0;
                _context.next = 3;
                return (0, _image.fetchImage)(this.props.src);

              case 3:
                this.image = _context.sent;
                _context.next = 10;
                break;

              case 6:
                _context.prev = 6;
                _context.t0 = _context['catch'](0);

                this.image = { width: 0, height: 0 };
                console.warn(_context.t0.message);

              case 10:
              case 'end':
                return _context.stop();
            }
          }
        }, _callee, this, [[0, 6]]);
      }));

      function fetch() {
        return _ref.apply(this, arguments);
      }

      return fetch;
    }()
  }, {
    key: 'render',
    value: function () {
      var _ref2 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2() {
        var margin, padding, _getAbsoluteLayout, left, top, containerWidth, containerHeight, imageWidth, xOffset;

        return regeneratorRuntime.wrap(function _callee2$(_context2) {
          while (1) {
            switch (_context2.prev = _context2.next) {
              case 0:
                margin = this.margin;
                padding = this.padding;
                _getAbsoluteLayout = this.getAbsoluteLayout(), left = _getAbsoluteLayout.left, top = _getAbsoluteLayout.top;


                this.drawBackgroundColor();
                this.drawBorders();

                if (this.props.debug) {
                  this.debug();
                }

                if (this.image.data) {
                  // Inner offset between yoga node and image box
                  // Makes image centered inside Yoga node
                  containerWidth = this.width - margin.right - margin.left;
                  containerHeight = this.height - margin.top - margin.bottom;
                  imageWidth = containerHeight * this.ratio;
                  xOffset = (containerWidth - imageWidth) / 2;


                  this.root.image(this.image.data, left + padding.left + xOffset, top + padding.top, { width: imageWidth, height: containerHeight });
                }

              case 7:
              case 'end':
                return _context2.stop();
            }
          }
        }, _callee2, this);
      }));

      function render() {
        return _ref2.apply(this, arguments);
      }

      return render;
    }()
  }, {
    key: 'ratio',
    get: function get() {
      return this.image.data ? this.image.width / this.image.height : 1;
    }
  }]);

  return Image;
}(_Base3.default);

Image.defaultProps = {
  wrap: false
};
exports.default = Image;