import { Injectable } from '@angular/core';
import { Observable, BehaviorSubject, fromEvent, Subject } from 'rxjs';
import { map, take } from 'rxjs/operators';
import { WindowRef } from './utils/window-ref.service';

@Injectable()
export class NativeContainerService {
  private wm: Observable<any>;
  public windowMessages = new Subject<any>();

  private webViewDetected = false;
  private webViewEventRecieved = false;

  constructor(private windowRef: WindowRef) {
    this.defineWindowCallback();

    this.wm = fromEvent(this.windowRef.nativeWindow, 'message').pipe(
      map((e: MessageEvent) => {
        console.dir(e);
        return e.data;
      })
    );

    this.wm.subscribe((data) => {
      if (data.status === 'INIT') {
        this.webViewEventRecieved = true;
      }
      this.windowMessages.next(data);
    });
  }

  public openScanner() {
    const scanRequest = {
      remissionProduct: true,
    };

    this.windowRef.nativeWindow.postMessage({ status: 'IN_PROGRESS', data: 'Scan Started' }, '*');

    if (this.isUiWebview()) {
      (this.windowRef.nativeWindow as any).webkit.messageHandlers.scanRequest.postMessage(scanRequest);
    } else {
      this.windowRef.nativeWindow.postMessage({ status: 'ERROR', data: 'Not a WebView' }, '*');
    }

    return this.windowMessages.asObservable();
  }

  public isUiWebview() {
    const navigator = this.windowRef.nativeWindow.navigator as Navigator;
    const standalone = (navigator as any).standalone,
      userAgent = navigator.userAgent.toLowerCase(),
      safari = /safari/.test(userAgent),
      ios = /iphone|ipod|ipad/.test(userAgent);

    this.webViewDetected = ios && !standalone && !safari;
    return this.webViewDetected || this.webViewEventRecieved;
  }

  private defineWindowCallback() {
    if (this.windowRef.nativeWindow['scanResults'] === undefined) {
      this.windowRef.nativeWindow['scanResults'] = (result) => window.postMessage(result, '*');
    }

    if (this.windowRef.nativeWindow['isRunningNative'] === undefined) {
      this.windowRef.nativeWindow['isRunningNative'] = (_) => window.postMessage({ status: 'INIT', data: 'Is a WebView' }, '*');
    }
  }
}
