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

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

export default class CookieConsent extends Component {
	static propTypes = {
		countryApi: PropTypes.string
	};

	static defaultProps = {
		countryApi: null
	};

	constructor(props) {
		super(props);

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

		this.state = {
			show: false,
			country: 'XX'
		};
	}

	componentDidMount() {
		if (localStorage.getItem('cookie-consent') === null) {
			if (this.props.countryApi) {
				this.getLocation();
			} else {
				this.setState({
					show: true
				});
			}
		}
	}

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

	async getLocation() {
		try {
			const data = await Axios.get(this.props.countryApi, { cancelToken: this.cancelSource.token });

			this.setState({
				country: data.data.country
			}, () => {
				this.setState({
					show: this.needConsent()
				});

				if (!this.needExplicitConsent()) {
					// Don't need explicit consent, so if they just continue on
					// we can presume to be in the clear
					this.consent(true);
				}
			});
		} catch (error) {
			this.setState({
				show: true
			});
		}
	}

	needConsent() {
		return [
			'AT',
			'BE',
			'BG',
			'CY',
			'CZ',
			'DE',
			'DK',
			'EE',
			'EL',
			'ES',
			'EU',
			'FI',
			'FR',
			'GB',
			'GR',
			'HR',
			'HU',
			'IE',
			'IT',
			'LT',
			'LU',
			'LV',
			'MT',
			'NL',
			'PL',
			'PT',
			'SE',
			'SK',
			'UK'
		].indexOf(this.state.country) >= 0;
	}

	needExplicitConsent() {
		return [
			'ES',
			'HR',
			'IT'
		].indexOf(this.state.country) >= 0;
	}

	consent(silent) {
		localStorage.setItem('cookie-consent', true);

		if (!silent) {
			this.setState({
				show: false
			});
		}
	}

	deny() {
		localStorage.setItem('cookie-consent', false);

		this.setState({
			show: false
		});
	}

	render() {
		return this.state.show ? (
			<div className={styles.CookieConsent}>
				<div className={styles.LeftContainer}>
					<p>
						This website uses cookies to deliver the best viewing experience.

						<a href="https://pinpoint.com/privacy" target="_blank" rel="noopener noreferrer">
							Learn more
						</a>
					</p>
				</div>
				<div className={styles.RightContainer}>
					<SemanticButton
						onClick={() => this.deny()}
						negative
					>
						Decline
					</SemanticButton>

					<SemanticButton
						onClick={() => this.consent()}
						positive
					>
						{
							this.needExplicitConsent() ? (
								'Allow Cookies'
							) : (
								'Got It'
							)
						}
					</SemanticButton>
				</div>
			</div>
		) : (
			<React.Fragment />
		);
	}
}
