<commit_before>import { Injectable } from '@angular/core';
import { stringify } from 'querystring';
import { ShareOutputBase } from '@picturepark/sdk-v1-angular';
import { ShareDetail } from '@picturepark/sdk-v1-angular';

function log(message: string) {
    if (console) {
        console.log(message);
    }
}

@Injectable({
    providedIn: 'root'
  })
export class FullscreenService {
  loading = false;
  scriptsPath = undefined;
  pictureparkShareCache: {[index: string]: ShareDetail}[] = {} as any;

  private loadedPlayers: any[] = [];

  showPrevious(token: string, elementId: string) {
    const share = this.pictureparkShareCache[token];
    const gallery = this.getGallery(elementId)!;

    if (share.player) {
      share.player.stop();
    }

    let newIndex = gallery.index - 1;
    if (newIndex < 0) {
      newIndex = gallery.children.length - 1;
    }

    this.showGalleryItem(gallery, newIndex);
  }

  showNext(token: string, elementId: string) {
    const share = this.pictureparkShareCache[token];
    const gallery = this.getGallery(elementId)!;

    if (share.player) {
      share.player.stop();
    }

    let newIndex = gallery.index + 1;
    if (newIndex === gallery.children.length) {
      newIndex = 0;
    }

    this.showGalleryItem(gallery, newIndex);
  }

  private showGalleryItem(gallery: any, newIndex: number) {
    if (gallery.index !== newIndex) {
      gallery.children[gallery.index].element.style.display = 'none';
      gallery.children[newIndex].element.style.display = '';
    }
  }

  private getGallery(elementId: string) {
    const children: {index: number, visible: Boolean, element: HTMLDivElement}[] = [];
    let visibleIndex = -1;

    const element = document.getElementById(elementId);
    if (element) {
      for (let i = 0; i < element.children.length; i++) {
        const child = element.children[i] as HTMLDivElement;
        const isVisible = child.style.display !== 'none';
        children.push({ index: i, visible: isVisible, element: child });
        if (isVisible) {
          visibleIndex = i;
        }
      }
      return { children: children, index: visibleIndex };
    } else {
      // no website gallery found (e.g. not available in the gallery template)
      return null;
    }
  }

  showDetail(token: string, shareItemId: string, widgetId: string) {
    if (this.loading) { return; }
    this.loading = true;

    const share = this.pictureparkShareCache[token];
    this.showDetailById(shareItemId, share.items, widgetId);
  }

  showDetailById(shareItemId: string, shareItems: IShareItem[], widgetId?: string) {
    const shareItem = shareItems.filter(i => i.id === shareItemId)[0];
    if (shareItem.isPdf && shareItems.length === 1) {
      this.showPdfJsItem(shareItem);
      this.loading = false;
    } else {
      const savedOverflow = document.body.style.overflow;
      document.body.style.overflow = 'hidden';
      this.showPhotoSwipeItem(shareItem, shareItems, widgetId ? 'gallery_' + widgetId : undefined).then(() => {
        this.loading = false;
        document.body.style.overflow = savedOverflow;
      });
    }
  }

  disposeVideoPlayer(player: any) {
    const existingPlayer = this.loadedPlayers.filter(p => p.element === player.id_)[0];
    if (existingPlayer) {
      log('Picturepark Widgets > Disposed videojs player');
      try {
        player.dispose();
      } catch {

      }
      this.loadedPlayers = this.loadedPlayers
        .filter(p => p.player !== player);
    } else {
      log('Picturepark Widgets > Player could not be disposed' + player);
    }
  }

  renderVideoPlayerIfNeeded(item: { previewUrl: string, originalUrl: string }, el: any, width: any, height: any) {
    let playerInfo = this.loadedPlayers.filter(p => p.element === el.id)[0];
    if (playerInfo) {
      return playerInfo.promise.then(player => {
        const element = document.getElementById(playerInfo.element)!;
          if (!element || !element.tagName || element.tagName.toLowerCase() === 'video' || element.tagName.toLowerCase() === 'audio') {
          if (player) {
            this.disposeVideoPlayer(player);
          }
          return this.renderVideoPlayer(element, item, width, height).then((renderedPlayer) => {
            playerInfo.player = renderedPlayer;
            log('Picturepark Widgets > Reloaded videojs player: ' + element.id);
            return renderedPlayer;
          });
        } else {
          log('Picturepark Widgets > Reused videojs player: ' + element.id);
          return player;
        }
      });
    }

    this.loadedPlayers = this.loadedPlayers.filter(p => p.element !== el.id_);

    playerInfo = {
      element: el.id,
      promise: this.renderVideoPlayer(el, item, width, height).then(player => {
        log('Picturepark Widgets > Created videojs player: ' + el.id);
        return player;
      })
    };

    this.loadedPlayers.push(playerInfo);
    return playerInfo.promise;
  }

  renderVideoPlayer(element, item, width, height) {
    return this.loadVideoPlayerLibraries().then((videojs) => {
      return new Promise<any>((resolve) => {
        const player = videojs(element, {
          autoplay: false,
          controls: true,
          poster: item.previewUrl,
          width: width,
          height: height,
          preload: 'auto'
        }, () => {
          resolve(player);
        });

          player.src({
              type: item.isMovie ? 'video/mp4' : 'audio/mp3',
              src: item.isMovie ? item.videoUrl : item.audioUrl
          });
        return player;
      });
    });
  }

  loadVideoPlayerLibraries() {
    if ((<any>window).videojs) {
      return Promise.resolve((<any>window).videojs);
    }

    return Promise.all([
      this.loadCss('https://vjs.zencdn.net/7.0.3/video-js.css'),
      this.loadScript('https://vjs.zencdn.net/7.0.3/video.js', 'videojs')
    ]).then(([_, videojs]) => {
      return videojs;
    });
  }

  showPdfJsItem(item) {
    const iframeElement = document.createElement('iframe');
    iframeElement.style.position = 'fixed';
    iframeElement.style.left = '0';
    iframeElement.style.top = '0';
    iframeElement.style.width = '100%';
    iframeElement.style.height = '100%';
    iframeElement.src = this.scriptsPath + 'pdfjs-dist/web/viewer.html?file=' + item.pdfUrl;

    const savedOverflow = document.body.style.overflow;
    const keydownCallback = (e: KeyboardEvent) => {
      // tslint:disable-next-line: deprecation
      const event = e || <KeyboardEvent>window.event;
      const isEscape = 'key' in event ? (event.key === 'Escape' || event.key === 'Esc') : ((<any>event).keyCode === 27);
      if (isEscape) {
        // tslint:disable-next-line: no-use-before-declare
        closeCallback();
      }
    };

    const closeCallback = () => {
      document.body.removeChild(iframeElement);
      document.body.style.overflow = savedOverflow;
      document.removeEventListener('keydown', keydownCallback, true);
    };

    let pdfLoaded = false;
    iframeElement.onload = (e) => {
      document.body.style.overflow = 'hidden';
      if (pdfLoaded) {
        closeCallback();
      } else {
        pdfLoaded = true;
      }
    };

    document.addEventListener('keydown', keydownCallback, true);
    document.body.appendChild(iframeElement);<commit_msg>PP9-8355: Cleanup fullscreen service.<commit_after>import { Injectable } from '@angular/core';
import { ShareOutputBase } from '@picturepark/sdk-v1-angular';

function log(message: string) {
    if (console) {
        console.log(message);
    }
}

@Injectable({
    providedIn: 'root'
  })
export class FullscreenService {
  loading = false;
  scriptsPath = undefined;

  private loadedPlayers: any[] = [];

  showDetailById(shareItemId: string, shareItems: IShareItem[], widgetId?: string) {
    const shareItem = shareItems.filter(i => i.id === shareItemId)[0];
    if (shareItem.isPdf && shareItems.length === 1) {
      this.showPdfJsItem(shareItem);
      this.loading = false;
    } else {
      const savedOverflow = document.body.style.overflow;
      document.body.style.overflow = 'hidden';
      this.showPhotoSwipeItem(shareItem, shareItems, widgetId ? 'gallery_' + widgetId : undefined).then(() => {
        this.loading = false;
        document.body.style.overflow = savedOverflow;
      });
    }
  }

  disposeVideoPlayer(player: any) {
    const existingPlayer = this.loadedPlayers.filter(p => p.element === player.id_)[0];
    if (existingPlayer) {
      log('Picturepark Widgets > Disposed videojs player');
      try {
        player.dispose();
      } catch {

      }
      this.loadedPlayers = this.loadedPlayers
        .filter(p => p.player !== player);
    } else {
      log('Picturepark Widgets > Player could not be disposed' + player);
    }
  }

  renderVideoPlayerIfNeeded(item: { previewUrl: string, originalUrl: string }, el: any, width: any, height: any) {
    let playerInfo = this.loadedPlayers.filter(p => p.element === el.id)[0];
    if (playerInfo) {
      return playerInfo.promise.then(player => {
        const element = document.getElementById(playerInfo.element)!;
          if (!element || !element.tagName || element.tagName.toLowerCase() === 'video' || element.tagName.toLowerCase() === 'audio') {
          if (player) {
            this.disposeVideoPlayer(player);
          }
          return this.renderVideoPlayer(element, item, width, height).then((renderedPlayer) => {
            playerInfo.player = renderedPlayer;
            log('Picturepark Widgets > Reloaded videojs player: ' + element.id);
            return renderedPlayer;
          });
        } else {
          log('Picturepark Widgets > Reused videojs player: ' + element.id);
          return player;
        }
      });
    }

    this.loadedPlayers = this.loadedPlayers.filter(p => p.element !== el.id_);

    playerInfo = {
      element: el.id,
      promise: this.renderVideoPlayer(el, item, width, height).then(player => {
        log('Picturepark Widgets > Created videojs player: ' + el.id);
        return player;
      })
    };

    this.loadedPlayers.push(playerInfo);
    return playerInfo.promise;
  }

  renderVideoPlayer(element, item, width, height) {
    return this.loadVideoPlayerLibraries().then((videojs) => {
      return new Promise<any>((resolve) => {
        const player = videojs(element, {
          autoplay: false,
          controls: true,
          poster: item.previewUrl,
          width: width,
          height: height,
          preload: 'auto'
        }, () => {
          resolve(player);
        });

          player.src({
              type: item.isMovie ? 'video/mp4' : 'audio/mp3',
              src: item.isMovie ? item.videoUrl : item.audioUrl
          });
        return player;
      });
    });
  }

  loadVideoPlayerLibraries() {
    if ((<any>window).videojs) {
      return Promise.resolve((<any>window).videojs);
    }

    return Promise.all([
      this.loadCss('https://vjs.zencdn.net/7.0.3/video-js.css'),
      this.loadScript('https://vjs.zencdn.net/7.0.3/video.js', 'videojs')
    ]).then(([_, videojs]) => {
      return videojs;
    });
  }

  showPdfJsItem(item) {
    const iframeElement = document.createElement('iframe');
    iframeElement.style.position = 'fixed';
    iframeElement.style.left = '0';
    iframeElement.style.top = '0';
    iframeElement.style.width = '100%';
    iframeElement.style.height = '100%';
    iframeElement.src = this.scriptsPath + 'pdfjs-dist/web/viewer.html?file=' + item.pdfUrl;

    const savedOverflow = document.body.style.overflow;
    const closeCallback = () => {
        document.body.removeChild(iframeElement);
        document.body.style.overflow = savedOverflow;
        // tslint:disable-next-line: no-use-before-declare
        document.removeEventListener('keydown', keydownCallback, true);
    };

    const keydownCallback = (e: KeyboardEvent) => {
      // tslint:disable-next-line: deprecation
      const event = e || <KeyboardEvent>window.event;
      const isEscape = 'key' in event ? (event.key === 'Escape' || event.key === 'Esc') : ((<any>event).keyCode === 27);
      if (isEscape) {
        closeCallback();
      }
    };

    let pdfLoaded = false;
    iframeElement.onload = (e) => {
      document.body.style.overflow = 'hidden';
      if (pdfLoaded) {
        closeCallback();
      } else {
        pdfLoaded = true;
      }
    };

    document.addEventListener('keydown', keydownCallback, true);
    document.body.appendChild(iframeElement);
{'fraction_non_alphanumeric': 0.14107485604606526, 'fraction_numerical': 0.0047184900831733845, 'mean_word_length': 2.677941176470588, 'pattern_counts': {'":': 0, '<': 15, '<?xml version=': 0, '>': 55, 'https://': 4, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5402357', 'n_tokens_mistral': 3856, 'n_tokens_neox': 3724, 'n_words': 746}