import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import Player from 'react-player';
import classNames from 'classnames';
import { capitalizeFirstLetter } from '../_helpers/tools';

import './media.scss';

class Media extends PureComponent {
  static propTypes = {
    /** @ignore */
    className: PropTypes.string,
    /** @ignore */
    children: PropTypes.node,
    src: PropTypes.string.isRequired,
    ratio: PropTypes.number,
    width: PropTypes.string,
    type: PropTypes.oneOf(['video', 'image']).isRequired,
    alt: PropTypes.string,
    name: PropTypes.string,
    cropped: PropTypes.bool,
    cover: PropTypes.bool,
    flexContainer: PropTypes.bool,
    border: PropTypes.bool
  };

  static defaultProps = {
    className: undefined,
    children: null,
    ratio: 1,
    width: null,
    alt: '',
    name: '',
    cropped: false,
    cover: false,
    flexContainer: false,
    border: false
  };

  render() {
    const {
      src, ratio, width, type, alt, name, className, cropped, cover, flexContainer, border, children, ...rest
    } = this.props;
    const ratioConverted = ratio < 0 ? 0 : (1 / ratio) * 100;
    return (
      <div
        styleName={classNames('media-wrapper', {
          'media-wrapper--bordered': border || children,
          'media-wrapper--flex-container': flexContainer
        })}
        className={className}
        style={{ width }}
        {...rest}
      >
        <div
          styleName="media-container"
          style={{ paddingTop: `${ratioConverted}%` }}
          itemType={`http://schema.org/${capitalizeFirstLetter(type)}Object`}
          itemScope
        >
          {
            type === 'image'
            && <div
              styleName={classNames(
                'media', 'media-img-wrapper', {
                  'media-img-wrapper--cover': cropped || cover,
                  'media-img-wrapper--height-auto': ratio < 0
                }
              )}
              style={{ backgroundImage: `url("${src}")` }}
            >
              <img
                styleName={classNames('media-img', {
                  'media-img--cover': cropped || cover,
                  'media-img--height-auto': ratio < 0
                })}
                src={src}
                alt={alt}
                itemProp="contentUrl"
              />
            </div>
          }
          {
            type === 'video'
            && <Player
              styleName="media"
              url={src}
              youtubeConfig={{ playerVars: { controls: 1 } }}
              controls
              itemProp="contentUrl"
              width={width}
              height="auto"
            />
          }
          {
            !!name
            && <span itemProp="caption" content={name} />
          }
        </div>
        { children && <div styleName="description">{ children }</div> }
      </div>
    );
  }
}

export default Media;
