import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot } from '@angular/router';
import { pressedKeys } from './utils/util';

@Injectable({
  providedIn: 'root'
})
export class RedirectGuard {
  //Previously parts of this required a "return true" or else the window navigation was cancelled.
  //Now it seems that a "return false" is required to prevent the RedirectComponent (empty screen) from being displayed,
  //especially when opening a link in a new tab.
  //For some reason during development, the current page often gets frozen when a new tab is opened with ctrl or shift.
  //This may be due to a bug in Chrome but it does not occur when running the published app in production mode.
  canActivate(route: ActivatedRouteSnapshot) {
    const externalUrl = route.paramMap.get('externalUrl');
    const isSameUrl = location.href.includes(externalUrl);
    const isShiftPressed = pressedKeys['Shift'];
    const openInNewTabByDefault = true; //set to false to open links in the same tab by default
    const isCtrlPressed = openInNewTabByDefault || pressedKeys['Control'];

    if (isShiftPressed) {
      window.open(externalUrl, '_blank');
      pressedKeys['Shift'] = false; //clear shift when opening a new window
      pressedKeys['Control'] = false; //clear ctrl when opening a new window
    }
    else if (isCtrlPressed) {
      window.open(externalUrl, '_blank');
    }
    else if (!isSameUrl) {
      window.open(externalUrl, '_self');
    }

    return false;
  }
}
