import React, { Component } from "react";
import {
	Platform,
	View,
	Modal,
	TouchableOpacity,
	StyleSheet,
} from "react-native";
import * as ScreenOrientation from "expo-screen-orientation";
import { StatusBarHeight, getCompressed, imageExists } from "../helper";
import { FontAwesome } from "./Icon";
import { SharingTools } from "./SharingTools";
import MediaPlayer from "./MediaPlayer";

class VideoPopup extends Component {
	constructor(props) {
		super(props);

		this.state = {
			uri: "",
			isFullScreen: false,
		};
	}

	UNSAFE_componentWillMount = async () => {
		this.checkCompressed(this.props.uri);
		await ScreenOrientation.lockAsync(
			Platform.OS === "ios"
				? ScreenOrientation.OrientationLock.DEFAULT
				: ScreenOrientation.OrientationLock.ALL,
		);
	};

	UNSAFE_componentWillReceiveProps(nextProps) {
		if (this.props.uri === nextProps.uri) return;
		this.checkCompressed(nextProps.uri);
	}

	componentWillUnmount = async () => {
		await ScreenOrientation.lockAsync(
			ScreenOrientation.OrientationLock.PORTRAIT_UP,
		);
	};

	checkCompressed = (url) => {
		const compressedUri = getCompressed(url);
		imageExists(compressedUri).then((compressedExists) => {
			this.setState({ uri: compressedExists ? compressedUri : url });
		});
	};

	renderClose() {
		return (
			<TouchableOpacity
				style={styles.menuIconContainer}
				onPress={this.props.onClose}
				activeOpacity={0.6}
			>
				<FontAwesome name="x" style={styles.menuIcon} />
			</TouchableOpacity>
		);
	}

	renderPlayer() {
		const { uri } = this.state;
		if (!uri) return null;

		return (
			<View style={styles.playerContainer}>
				<MediaPlayer
					source={uri}
					useVideoPlayer={true}
					autoPlay={true}
					orientationChanged={(isFullScreen) => this.setState({ isFullScreen })}
				/>
			</View>
		);
	}

	render() {
		const { isFullScreen } = this.state;
		const { visible, onClose, animationType, style } = this.props;

		return (
			<Modal
				visible={visible}
				animationType={animationType || "fade"}
				onRequestClose={onClose}
				style={[styles.container, style]}
				supportedOrientations={["portrait", "landscape"]}
			>
				{this.renderPlayer()}
				{!isFullScreen && this.renderClose()}
				{!isFullScreen && <SharingTools uri={this.props.uri} />}
			</Modal>
		);
	}
}

const styles = StyleSheet.create({
	container: {
		backgroundColor: "#000",
	},
	menuIconContainer: {
		position: "absolute",
		top: StatusBarHeight(0),
		right: 0,
		width: 55,
		height: 55,
		zIndex: 3,
	},
	menuIcon: {
		fontSize: 25,
		padding: 15,
		width: 55,
		textAlign: "center",
		color: "#fff",
		zIndex: 3,
	},
	playerContainer: {
		flex: 1,
		backgroundColor: "#000",
		alignItems: "center",
		justifyContent: "center",
	},
});

export { VideoPopup };
