import { ipcRenderer } from 'electron';

import { Observable } from 'rxjs';

import { NativeService } from '@ucap-webmessenger/native';
import { Channel } from '../types/channel.type';

export class ElectronNativeService implements NativeService {
  showNotify(
    roomSeq: number,
    title: string,
    contents: string,
    image: string,
    useSound: boolean
  ): void {
    ipcRenderer.send(
      Channel.showNotify,
      roomSeq,
      title,
      contents,
      image,
      useSound
    );
  }

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

  showImageViewer(): void {
    ipcRenderer.send(Channel.showImageViewer);
  }

  readFile(path: string): Observable<ArrayBuffer> {
    return new Observable<ArrayBuffer>(subscriber => {
      try {
        subscriber.next(ipcRenderer.sendSync(Channel.readFile, path));
      } catch (error) {
        subscriber.error(error);
      } finally {
        subscriber.complete();
      }
    });
  }

  saveFile(path: string, buf: ArrayBuffer): Observable<boolean> {
    return new Observable<boolean>(subscriber => {
      try {
        subscriber.next(ipcRenderer.sendSync(Channel.saveFile, path, buf));
      } catch (error) {
        subscriber.error(error);
      } finally {
        subscriber.complete();
      }
    });
  }

  constructor() {}
}
