import { Injectable } from '@angular/core';
import { NatsService } from 'app/core/nats/services/nats.service';

import { Error } from 'app/modules/proto/protobuf/rpc_pb';

import {
  ListGamesRequest,
  ListGamesResponse,
} from 'app/modules/proto/c2se/api/game_pb';
import { SUBJECT_LIST_GAMES } from 'app/modules/proto/c2se/frontend/api/game_pb';

@Injectable({
  providedIn: 'root',
})
export class GameService {
  /**
   * Constructor
   */
  constructor(private __natsService: NatsService) {}

  // -----------------------------------------------------------------------------------------------------
  // @ Accessors
  // -----------------------------------------------------------------------------------------------------

  // -----------------------------------------------------------------------------------------------------
  // @ Public methods
  // -----------------------------------------------------------------------------------------------------

  listGames(vendorId: number): Promise<ListGamesResponse.Result> {
    return new Promise<ListGamesResponse.Result>((resolve, reject) => {
      let search = new ListGamesRequest.Search();
      search.setVendorId(vendorId);
      let req = new ListGamesRequest();
      req.setSearch(search);

      this.__natsService
        .request<ListGamesResponse.Result>(
          SUBJECT_LIST_GAMES,
          req.serializeBinary(),
          ListGamesResponse.deserializeBinary
        )
        .then((result) => {
          console.log('success', result, result.getGamesList());
          return resolve(result);
        })
        .catch((e: Error) => {
          console.log('failed', e);
          reject(e);
        });
    });
  }
}
