import React from 'react';
import shallowCompare from 'react-addons-shallow-compare';
import {classNames, compose as composeStyle, ease} from 'react-dom-stylesheet';

export default class Image extends React.Component {

  static displayName = 'Image'

  static propTypes = {
    src: React.PropTypes.string.isRequired,
    l10n: React.PropTypes.object,
    className: React.PropTypes.string,
    alt: React.PropTypes.string,
    hidden: React.PropTypes.bool,
    width: React.PropTypes.number,
    height: React.PropTypes.number,
    onImageLoaded: React.PropTypes.func
  }

  static defaultProps = {
    hidden: false
  }

  state = {
    isLoaded: false
  }

  shouldComponentUpdate (nextProps, nextState) {
    return shallowCompare(this, nextProps, nextState);
  }

  render () {
    const {
      l10n,
      className,
      src,
      alt,
      width,
      height,
      hidden
    } = this.props;

    const {isLoaded} = this.state;

    const imageStyle = composeStyle({
      image: {
        transition: ease('linear')
      }
    });

    const rootClasses = classNames('image', {
      loaded: isLoaded
    }, className);

    return (
      <div className={rootClasses}>
        <img src={src}
             style={imageStyle}
             alt={alt || 'image'}
             hidden={!this.state.isLoaded ? true : null}
             onLoad={this._onImageLoaded}
             role='presentation'
             width={width}
             height={height}
             aria-hidden={hidden ? true : null}
             data-l10n-id={l10n && l10n.title ? 'image' : null}
             data-l10n-args={l10n && l10n.title ? JSON.stringify(l10n) : null}/>
      </div>
    );
  }

  _onImageLoaded = () => {
    if (!this.state.isLoaded) {
      this.setState({
        isLoaded: true
      });

      if (this.props.onImageLoaded) this.props.onImageLoaded();
    }
  }
}
