import * as AWS from 'aws-sdk/global';
// import Config from '@botsbotsbots/common/config';
import Storage from '../utils/localstorage';
const scopes = [
	'bot',
	'files:write:user',
	'files:read',
	'links:read',
	'links:write',
	'channels:read',
	'channels:history',
	'team:read',
	'emoji:read',
	'users:read'
];
const { SLACK_CLIENT_ID } = process.env;

export async function makeIdentityId() {
	AWS.config.region = 'us-west-2';
	const creds = new AWS.CognitoIdentityCredentials(
		{
			IdentityPoolId: <string>process.env.COGNITO_IDENTITY_POOL_ID
		},
		{
			region: <string>process.env.AWS_REGION
		}
	);
	await creds.getPromise();
	AWS.config.credentials = creds;
	if (!creds.identityId) {
		return Promise.reject(new Error('Expected identityId'));
	}
	// await Storage.setItem("bbb-id", creds.identityId);
	return creds.identityId;
}

export function getOauthUrl(identityId) {
	return `https://slack.com/oauth/authorize?client_id=${SLACK_CLIENT_ID}&scope=${scopes.join(
		','
	)}&state=${encodeURIComponent(identityId)}&redirect_uri=${encodeURIComponent(
		`https://www.botsbotsbots.party/oauth`
	)}`;
}

function doRedirect(identityId) {
	const redirectUri = getOauthUrl(identityId);
	window.location.replace(redirectUri);
}

export async function getIdentityId(): Promise<string> {
	let bbbId = await Storage.getItem('bbb-id');
	let identityId;
	if (bbbId) {
		identityId = bbbId;
	} else {
		identityId = await makeIdentityId();
	}
	return identityId;
}

export async function maybeRedirect(): Promise<string | void> {
	const identityId = await getIdentityId();
	console.log('retrieved identity: ' + identityId);
	await Storage.setItem('bbb-id', identityId);
	window.location.replace(getOauthUrl(identityId));
}
