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

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

import {
  ListBanksRequest,
  ListBanksResponse,
  GetBankResponse,
  GetBankRequest,
} from 'app/modules/proto/c2se/bank_pb';
import {
  SUBJECT_LIST_BANKS,
  SUBJECT_GET_BANK,
} from 'app/modules/proto/c2se/frontend/bank_pb';

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

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

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

  listBanks(): Promise<ListBanksResponse.Result> {
    return new Promise<ListBanksResponse.Result>((resolve, reject) => {
      let req = new ListBanksRequest();

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

  getBank(): Promise<GetBankResponse.Result> {
    return new Promise<GetBankResponse.Result>((resolve, reject) => {
      let req = new GetBankRequest();

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

}
