import React from 'react';
import {
	ActivityIndicator,
	Dimensions,
	View,
	StyleSheet,
} from 'react-native';
import { color } from 'nixplay-ui-kit';
import PropTypes from 'prop-types';
import FastImage from 'react-native-fast-image';

const { width: screenWidth, height: screenHeight } = Dimensions.get('window');

const styles = StyleSheet.create({
	container: {
		height: screenHeight,
		width: screenWidth,
		justifyContent: 'center',
		alignItems: 'center',
		backgroundColor: 'black',
	},
	portrait: {
		width: screenWidth,
		height: screenHeight,
	},
	landscape: {
		width: screenHeight,
		height: screenWidth,
	},
	loadingContainer: {
		position: 'absolute',
		alignItems: 'center',
		justifyContent: 'center',
		top: 0,
		right: 0,
		left: 0,
		bottom: 0,
	},
});


export default class PhotoContent extends React.Component {
	static propTypes = {
		index: PropTypes.number.isRequired,
		item: PropTypes.object.isRequired,
		onImageLoad: PropTypes.func,
	}

	static defaultProps = {
		onImageLoad: () => {},
	}

	constructor(props) {
		super(props);

		this.state = {
			isLoading: true,
		};
	}

	onImageLoad = ({ nativeEvent }) => {
		const { width, height } = nativeEvent;
		const { index, onImageLoad, item } = this.props;
		this.setState({
			isLoading: false,
		}, () => {
			onImageLoad({
				width, height, index, url: item.previewUrl,
			});
		});
	}

	render() {
		const { previewUrl, rotation } = this.props.item;
		const isPortrait = (rotation === 0 || rotation % 180 === 0);
		const { isLoading } = this.state;
		return (
			<View style={styles.container}>
				<FastImage
					style={[rotation ? {
						transform: [{
							rotate: `${rotation}deg`,
						}],
					} : {}, isPortrait ? styles.portrait : styles.landscape]}
					source={{ uri: previewUrl }}
					resizeMode={FastImage.resizeMode.contain}
					onLoad={this.onImageLoad}
				/>
				{isLoading && <View style={styles.loadingContainer}><ActivityIndicator size="large" color={color.blue} /></View>}
			</View>
		);
	}
}
