import React, { Component } from 'react';
import PropTypes from 'prop-types';
import Axios from 'axios';
import {
	Image as SemanticImage
} from 'semantic-ui-react';

import * as styles from './Style.less';

import Empty from './empty.png';

export default class Avatar extends Component {
	static propTypes = {
		src: PropTypes.string,
		large: PropTypes.bool
	};

	static defaultProps = {
		src: null,
		large: false
	};

	constructor(props) {
		super(props);

		this.cancelSource = Axios.CancelToken.source();

		this.state = {
			image: null,
			loaded: false
		};
	}

	componentDidMount() {
		if (!this.props.src) {
			this.setState({
				loaded: true
			});
		}
	}

	componentWillReceiveProps(nextProps) {
		this.setState({
			image: nextProps.src
		});
	}

	componentWillUnmount() {
		this.cancelSource.cancel();
	}

	render() {
		if (this.state.loaded && this.state.image) {
			return (
				<SemanticImage
					src={this.state.image}
					className={`${styles.Avatar}${this.props.large ? ' large' : ''}`}
				/>
			);
		}

		return (
			<SemanticImage
				src={Empty}
				className={`${styles.Avatar}${this.props.large ? ' large' : ''}`}
			/>
		);
	}
}
