import * as React from 'react';
import { Helmet } from 'react-helmet';

declare global {
	interface Window {
		IGLOO: any;
	}
}

interface IovationProps {
	onChange?: (name: string, value: any) => void;
	name?: string;
	value?: { ip?: string; blackBox?: string };
}

interface IovationState {
	ip?: string;
	blackBox?: string;
}

export default class Iovation extends React.Component<IovationProps, IovationState> {
	state = {
		ip: '',
		blackBox: ''
	};

	shouldComponentUpdate() {
		return false;
	}

	componentDidMount() {
		if (!window.sessionStorage.getItem('iovation')) {
			this.getBlackBox();
			console.log('helloooooooooooooooooooooo');

			// axios
			// 	.get('/iovation/getIP')
			// 	.then(response => {
			// 		let iovation = this.props.value;
			// 		this.setState({
			// 			ip: response.data.data.ip
			// 		});
			// 		if (this.state.blackBox) {
			// 			this.props.onChange(
			// 				this.props.name || 'iovation',
			// 				Object.assign({}, iovation, {
			// 					ip: response.data.data.ip,
			// 					blackBox: this.state.blackBox
			// 				})
			// 			);
			// 		}
			// 	})
			// 	.catch(error => {});
		}
	}

	getBlackBox = () => {
		let blackbox = { finished: false, blackbox: '' };
		if (window.IGLOO && window.IGLOO.getBlackbox) {
			blackbox = window.IGLOO.getBlackbox() as { blackbox: string; finished: boolean };
		}

		let iovation = this.props.value;

		if (!blackbox.finished) {
			setTimeout(this.getBlackBox, 500);
		}

		if (blackbox.blackbox) {
			this.setState({
				blackBox: blackbox.blackbox
			});
			if (this.state.ip) {
				this.props.onChange(
					this.props.name || 'iovation',
					Object.assign({}, iovation, { blackBox: blackbox.blackbox, ip: this.state.ip })
				);
			}
		}
	};

	render() {
		return (
			!window.sessionStorage.getItem('iovation') && (
				<React.Fragment>
					<Helmet>
						<script src="/public/scripts/iovation.config.js" />
						<script src="/public/scripts/iovation.js" />
					</Helmet>
				</React.Fragment>
			)
		);
	}
}
