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/protobuf/protobuf/rpc/error_pb';

import {
  ListSitesRequest,
  ListSitesResponse,
  CreateSiteRequest,
  CreateSiteResponse,
  UpdateSiteRequest,
  UpdateSiteResponse,
  DeleteSiteRequest,
  DeleteSiteResponse,
  SUBJECT_LIST_SITES,
  SUBJECT_CREATE_SITE,
  SUBJECT_UPDATE_SITE,
  SUBJECT_DELETE_SITE,
} from 'app/modules/protobuf/c2se/backend/site_pb';
import { Site } from 'app/modules/protobuf/models/domain/site_pb';

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

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

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

  listSites(): Promise<ListSitesResponse.Result> {
    return new Promise<ListSitesResponse.Result>((resolve, reject) => {
      let req = new ListSitesRequest();

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

  createSite(): Promise<CreateSiteResponse.Result> {
    return new Promise<CreateSiteResponse.Result>((resolve, reject) => {
      let req = new CreateSiteRequest();

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