import * as vscode from 'vscode';
import { OPEN_GETTING_STARTED_COMMAND } from '../theia/command';
import BriefingView from '../view/briefingView';
import GettingStartedView from '../view/gettingStartedView';
import { CHOOSE_MISSION_WORKDIR_COMMAND, CommandHandler } from './commandHandler';
import ExtensionStore from './extensionStore';
import KeycloakOAuth2DeviceFlowConnection from './keycloakOAuth2DeviceFlowConnection';

export default class Controller {
	public connection: KeycloakOAuth2DeviceFlowConnection;
	private commandHandler: CommandHandler;
	private briefingView;
	private gettingStartedView: GettingStartedView;
	constructor(private context: vscode.ExtensionContext) {
		this.briefingView = new BriefingView();
		this.gettingStartedView = new GettingStartedView(context.extensionUri);
		this.commandHandler = new CommandHandler(this);
		this.connection = new KeycloakOAuth2DeviceFlowConnection(
			'https://auth.dev.deadlock.io/auth/realms/Deadlock/protocol/openid-connect/auth/device',
			'https://auth.dev.deadlock.io/auth/realms/Deadlock/protocol/openid-connect/token',
			'https://auth.dev.deadlock.io/auth/realms/Deadlock/protocol/openid-connect/userinfo',
		);

		const that = this;
		vscode.window.registerUriHandler({
			handleUri(uri: vscode.Uri) {
				const queryParams: URLSearchParams = new URLSearchParams(uri.query);
				const action: string | null = queryParams.get('action');

				switch (action) {
					case 'open-challenge':
						that.launchMission(queryParams.get('missionId'));
						break;

					default:
						vscode.window.showInformationMessage('Aucune action trouvée!');
				}
			},
		});
	}
	async authenticate() {
		const tokens = await this.connection.getToken({ openLink: Controller.openBrowserWithUrl });
		const exensionStorage = ExtensionStore.getInstance();
		await exensionStorage.setAccessToken(tokens.accessToken);
		await exensionStorage.setRefreshToken(tokens.refreshToken);
		this.gettingStartedView.isAlreadyConnected = !!(await exensionStorage.getAccessToken());
	}
	public static openBrowserWithUrl(url: string) {
		vscode.commands.executeCommand('vscode.open', vscode.Uri.parse(url));
	}

	async launchMission(missionId: string | null) {
		if (missionId) {
			vscode.window.showInformationMessage(`vous lancez la mission ${missionId}`);
			const extensionStore = ExtensionStore.getInstance();
			const hadMissionWorkdir = extensionStore.getMissionWorkdir() !== undefined;
			if (!hadMissionWorkdir) {
				await vscode.commands.executeCommand(CHOOSE_MISSION_WORKDIR_COMMAND.cmd);
			}

			const hadBeenConnected = (await extensionStore.getAccessToken()) !== undefined;
			console.log('accesToke: ' + extensionStore.getAccessToken());

			if (!hadBeenConnected) {
				const { accessToken, refreshToken } = await this.connection.getToken({
					openLink: Controller.openBrowserWithUrl,
				});
				vscode.window.showInformationMessage('Nouvelle connexion validée');
			} else {
				vscode.window.showInformationMessage('Déjà connecté: session récupérée');
			}

			vscode.commands.executeCommand(OPEN_GETTING_STARTED_COMMAND.cmd);
		}
	}
}