import auth0 from 'auth0-js';
import Config from '@botsbotsbots/common/config';
import TokenVerifier from '@botsbotsbots/common/auth/token';
const ID_TOKEN_KEY = 'id_token';
const ACCESS_TOKEN_KEY = 'access_token';

const CLIENT_ID = Config.auth.clientId;
const CLIENT_DOMAIN = Config.auth.domain;
const REDIRECT = 'http://localhost:5000/callback';
const SCOPE = 'openid profile read:graphql';
const AUDIENCE = Config.auth.clientId;

var auth = new auth0.WebAuth({
	clientID: CLIENT_ID,
	domain: CLIENT_DOMAIN
});

export function login() {
	auth.authorize({
		connection: 'slack',
		responseType: 'token id_token',
		redirectUri: REDIRECT,
		audience: `https://${CLIENT_DOMAIN}/userinfo`,
		scope: SCOPE
	});
}

export function logout() {
	clearIdToken();
	clearAccessToken();
	clearProfile();
	window.history.pushState('/');
}

export function requireAuth(nextState, replace) {
	if (!isLoggedIn()) {
		replace({ pathname: '/' });
	}
}

export function getIdToken() {
	return localStorage.getItem(ID_TOKEN_KEY);
}

export function getAccessToken() {
	return localStorage.getItem(ACCESS_TOKEN_KEY);
}

function clearIdToken() {
	localStorage.removeItem(ID_TOKEN_KEY);
}

function clearAccessToken() {
	localStorage.removeItem(ACCESS_TOKEN_KEY);
}

function clearProfile() {
	localStorage.removeItem('profile');
}

// Helper function that will allow us to extract the access_token and id_token
export function getAndStoreParameters() {
	auth.parseHash(window.location.hash, function(err, authResult) {
		if (err) {
			return console.log(err);
		}

		setIdToken(authResult.idToken);
		setAccessToken(authResult.accessToken);
	});
}

export function getEmail(): any | undefined {
	return getProfile().email;
}

export function getName() {
	return getProfile().nickname;
}

// Get and store access_token in local storage
export function setAccessToken(accessToken) {
	localStorage.setItem(ACCESS_TOKEN_KEY, accessToken);
}

// Get and store id_token in local storage
function setIdToken(idToken) {
	localStorage.setItem(ID_TOKEN_KEY, idToken);
}

export function isLoggedIn() {
	const idToken = getIdToken();
	return !!idToken && !isTokenExpired(idToken);
}

export function getProfile() {
	const tokenString = getIdToken();
	if (!tokenString) {
		return Object.create(null);
	}
	const token = new TokenVerifier(tokenString);
	return token.safeDecode || Object.create(null);
}

export function getUser() {
	return new Promise((resolve, reject) => {
		const accessToken = getAccessToken();
		if (!accessToken) {
			return reject(new Error('No access token'));
		}
		auth0.client.userInfo(getAccessToken(), (err, user) => (err ? reject(err) : resolve(user)));
	});
}

function getTokenExpirationDate(encodedToken) {
	const token = new TokenVerifier(encodedToken).payload;
	if (!token.exp) {
		return 1;
	}

	const date = new Date(0);
	date.setUTCSeconds(token.exp);

	return date;
}

function isTokenExpired(token) {
	const expirationDate = getTokenExpirationDate(token);
	return expirationDate < new Date();
}
// }
// export default class Auth {
// 	auth0: any;

// 	userInfo = null;

// 	constructor({ domain, clientId, callbackUrl }) {
// 		this.login = this.login.bind(this);
// 		this.logout = this.logout.bind(this);
// 		this.handleAuthentication = this.handleAuthentication.bind(this);
// 		this.isAuthenticated = this.isAuthenticated.bind(this);
// 		this.auth0 = new auth0.WebAuth({
// 			domain,
// 			clientID: clientId,
// 			redirectUri: callbackUrl,
// 			audience: `https://${domain}/userinfo`,
// 			responseType: 'token id_token'
// 		});
// 	}

// 	login() {
// 		this.auth0.authorize({ connection: 'slack', scope: 'openid profile read:graphql' });
// 	}

// 	handleAuthentication() {
// 		this.auth0.parseHash((err, authResult) => {
// 			if (authResult && authResult.accessToken && authResult.idToken) {
// 				this.setSession(authResult);
// 			} else if (err) {
// 				console.log(err);
// 				alert(`Error: ${err.error}. Check the console for further details.`);
// 			}
// 		});
// 	}

// 	get access_token() {
// 		return localStorage.getItem('access_token') || null;
// 	}

// 	get id_token() {
// 		return localStorage.getItem('id_token') || null;
// 	}

// 	setSession(authResult) {
// 		console.log(authResult);
// 		// Set the time that the access token will expire at
// 		let expiresAt = JSON.stringify(authResult.expiresIn * 1000 + new Date().getTime());
// 		this.auth0.client.userInfo(authResult.accessToken, function(err, user) {
// 			if (err) {
// 				console.error(err);
// 				return;
// 			}
// 			localStorage.setItem('access_token', authResult.accessToken);
// 			localStorage.setItem('id_token', authResult.idToken);
// 			localStorage.setItem('expires_at', expiresAt);
// 			// Now you have the user's information
// 			localStorage.setItem('user_info', JSON.stringify(user));
// 		});
// 	}

// 	currentUser() {
// 		if (this.isAuthenticated()) {
// 			const user = localStorage.getItem('user_info');
// 			if (!user) {
// 				throw new Error('Missing user info');
// 			}
// 			return JSON.parse(user);
// 		} else {
// 			return null;
// 		}
// 	}

// 	logout() {
// 		// Clear access token and ID token from local storage
// 		localStorage.removeItem('access_token');
// 		localStorage.removeItem('id_token');
// 		localStorage.removeItem('user_info');
// 		localStorage.removeItem('expires_at');
// 		// navigate to the home route
// 	}

// 	isAuthenticated() {
// 		// Check whether the current time is past the
// 		// access token's expiry time

// 		let expiresAt = JSON.parse(localStorage.getItem('expires_at') || '1');
// 		return new Date().getTime() < expiresAt;
// 	}
// }
