import { grpc } from '@improbable-eng/grpc-web';
import { MediaSetService } from './generated/media_set_pb_service';
import {
  MediaSet,
  GetRequest,
  GetAudioProgress,
  GetAudioRequest,
} from './generated/media_set_pb';

export const GetMediaSet = (
  host: string,
  request: GetRequest
): Promise<MediaSet> => {
  return new Promise<MediaSet>((resolve, reject) => {
    let result: MediaSet;

    grpc.invoke(MediaSetService.Get, {
      host: host,
      request: request,
      onMessage: (mediaSet: MediaSet) => {
        result = mediaSet;
      },
      onEnd: (
        code: grpc.Code,
        msg: string | undefined,
        _trailers: grpc.Metadata
      ) => {
        if (code != 0) {
          reject(new Error(`unexpected grpc code: ${code}, message: ${msg}`));
          return;
        }
        resolve(result);
      },
    });
  });
};

// export const etchMediaSetAudio = (
//   host: string,
//   request: FetchAudioRequest,
//   onProgress: { (progress: FetchAudioProgress): void }
// ) => {
//   grpc.invoke(FetchService.FetchAudio, {
//     host: 'http://localhost:8888',
//     request: request,
//     onMessage: onProgress,
//     onEnd: (
//       code: grpc.Code,
//       msg: string | undefined,
//       trailers: grpc.Metadata
//     ) => {
//       console.log('fetch audio request ended');
//     },
//   });
// };
