import { Observable } from 'rxjs';

import {
  NativeService,
  WindowState,
  NotificationRequest,
  WindowIdle
} from '@ucap-webmessenger/native';
import { HttpClient } from '@angular/common/http';
import { map } from 'rxjs/operators';

export class BrowserNativeService implements NativeService {
  notify(noti: NotificationRequest): void {}
  closeAllNotify(): void {}

  checkForUpdates(): Observable<boolean> {
    return new Observable<boolean>(subscriber => {
      try {
        subscriber.next(false);
      } catch (error) {
        subscriber.error(error);
      } finally {
        subscriber.complete();
      }
    });
  }

  showImageViewer(): void {}

  readFile(path: string): Observable<Buffer> {
    return this.httpClient.get(path, { responseType: 'arraybuffer' }).pipe(
      map(arrayBuffer => {
        return Buffer.from(arrayBuffer);
      })
    );
  }

  saveFile(
    buffer: Buffer,
    fileName: string,
    path?: string
  ): Observable<string> {
    return this.httpClient.post<string>(path, buffer, {});
  }

  windowStateChanged(): Observable<WindowState> {
    return new Observable<WindowState>(subscriber => {
      try {
        subscriber.next(WindowState.Normal);
      } catch (error) {
        subscriber.error(error);
      } finally {
        subscriber.complete();
      }
    });
  }

  windowClose(): void {}

  windowMinimize(): void {}

  windowMaximize(): void {}

  idleStateChanged(): Observable<WindowIdle> {
    return new Observable<WindowIdle>(subscriber => {
      try {
        subscriber.next(WindowIdle.Active);
      } catch (error) {
        subscriber.error(error);
      } finally {
        subscriber.complete();
      }
    });
  }

  constructor(private httpClient: HttpClient) {}
}
