import { INavDetail, INavRunHttpClient, INavRunHttpProjectDetail, INavRunSchemaDesignerDetail } from '../../events/NavigationEvents.js';
import { NavigationBindings } from '../base/NavigationBindings.js';

export class WebNavigationBindings extends NavigationBindings {
  handles = new Map<string, Window>();

  protected open(id: string, url: string, sameWindow = false): void {
    if (sameWindow) {
      window.location.href = url;
      return;
    }
    if (this.handles.has(id)) {
      const handle = this.handles.get(id) as Window;
      if (!handle.closed) {
        // handle.blur();
        // setTimeout(handle.focus, 0);
        // handle.location.href = url;
        return;
      }
    }
    const win = window.open(url);
    if (!win) {
      throw new Error(`Window blocked. Don't use timers and callbacks when creating a window.`);
    }
    this.handles.set(id, window);
    const handler = (): void => {
      this.handles.delete(id);
      window.removeEventListener('beforeunload', handler);
    }
    window.addEventListener('beforeunload', handler);
  }

  async openStoreConfiguration(): Promise<void> {
    const url = this.getPageUrl('../api-client/config.html').toString();
    this.open(url, url);
  }

  async openApiClient(init: INavRunHttpClient = {}): Promise<void> {
    const url = this.getPageUrl('../api-client/main.html');
    const { sameWindow, space } = init;
    if (space) {
      url.searchParams.set('space', space);
    }
    const id = url.toString();
    this.open(id, id, sameWindow);
  }

  async openHttpProject(init: INavRunHttpProjectDetail): Promise<void> {
    const url = this.getPageUrl('../http-project/main.html');
    const { sameWindow, space, key } = init;
    if (!space) {
      throw new Error(`Unable to complete navigation. The "space" parameter is required.`);
    }
    if (!key) {
      throw new Error(`Unable to complete navigation. The "key" parameter is required.`);
    }
    url.searchParams.set('space', space);
    url.searchParams.set('key', key);
    const id = url.toString();
    this.open(id, id, sameWindow);
  }
  
  async openStoreAuthenticate(init: INavDetail = {}): Promise<void> {
    const url = this.getPageUrl('../api-client/authenticate.html').toString();
    this.open(url, url, init.sameWindow);
  }

  async openTelemetry(init: INavDetail = {}): Promise<void> {
    const url = this.getPageUrl('../api-client/telemetry.html').toString();
    this.open(url, url, init.sameWindow);
  }

  async openSchemaDesigner(init: INavRunSchemaDesignerDetail): Promise<void> {
    const uri = this.getPageUrl('../schema-design/main.html');
    const { key, sameWindow } = init;
    uri.searchParams.set('key', key);
    uri.searchParams.set('space', init.space);
    const url = uri.toString();
    this.open(url, url, sameWindow);
  }
}
