import * as plugins from '../plugins.js';
import { Cloudly } from '../classes.cloudly.js';
import { ExternalRegistry } from './classes.externalregistry.js';

export class ExternalRegistryManager {
  public cloudlyRef: Cloudly;
  public typedrouter = new plugins.typedrequest.TypedRouter();
  public CExternalRegistry = plugins.smartdata.setDefaultManagerForDoc(this, ExternalRegistry);

  get db() {
    return this.cloudlyRef.mongodbConnector.smartdataDb;
  }

  constructor(cloudlyRef: Cloudly) {
    this.cloudlyRef = cloudlyRef;
  }

  public async start() {
    // lets set up a typedrouter
    this.typedrouter.addTypedRouter(this.typedrouter);

    this.typedrouter.addTypedHandler<plugins.servezoneInterfaces.requests.externalRegistry.IReq_GetRegistryById>(
      new plugins.typedrequest.TypedHandler('getExternalRegistryById', async (dataArg) => {
        const registry = await ExternalRegistry.getRegistryById(dataArg.id);
        return {
          registry: await registry.createSavableObject(),
        };
      })
    );

    this.typedrouter.addTypedHandler<plugins.servezoneInterfaces.requests.externalRegistry.IReq_GetRegistries>(
      new plugins.typedrequest.TypedHandler('getExternalRegistries', async (dataArg) => {
        const registries = await ExternalRegistry.getRegistries();
        return {
          registries: await Promise.all(
            registries.map((registry) => registry.createSavableObject())
          ),
        };
      })
    );

    this.typedrouter.addTypedHandler<plugins.servezoneInterfaces.requests.externalRegistry.IReq_CreateRegistry>(
      new plugins.typedrequest.TypedHandler('createExternalRegistry', async (dataArg) => {
        const registry = await ExternalRegistry.createExternalRegistry(dataArg.registryData);
        return {
          registry: await registry.createSavableObject(),
        };
      })
    );
  }
}