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

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

import {
  UpdateMemberReferrerRequest,
  UpdateMemberReferrerResponse,
  DeleteMemberReferrerRequest,
  DeleteMemberReferrerResponse,
  GetMemberReferrerByCodeResponse,
  GetMemberReferrerByCodeRequest,
} from 'app/modules/proto/c2se/member_referrer_pb';
import { SUBJECT_GET_MEMBER_REFERRER_BY_CODE } from 'app/modules/proto/c2se/frontend/member_referrer_pb';

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

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

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

  getMemberReferrerByCode(
    code: string
  ): Promise<GetMemberReferrerByCodeResponse.Result> {
    return new Promise<GetMemberReferrerByCodeResponse.Result>(
      (resolve, reject) => {
        let req = new GetMemberReferrerByCodeRequest();

        req.setCode(code);

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