import { ConnectionManager, Connector } from '@things-factory/integration-base'

const debug = require('debug')('aidoop:integration-base:flow-sync-connector')

export class FlowSyncConnector implements Connector {
  async ready(connectionConfigs) {
    await Promise.all(connectionConfigs.map(this.connect.bind(this)))

    ConnectionManager.logger.info('flow-sync-connector connections are ready')
  }

  async connect(connection) {
    var { params } = connection

    var waitCount = 0
    var releaseCount = 0
    ConnectionManager.addConnectionInstance(connection, {
      ...connection,
      params,
      waitCount,
      releaseCount
    })

    ConnectionManager.logger.info(
      `flow-sync-connector connection(${connection.name}:${connection.endpoint}) is connected`
    )
  }

  async disconnect(connection) {
    ConnectionManager.removeConnectionInstance(connection)

    ConnectionManager.logger.info(`flow-sync-connector connection(${connection.name}) is disconnected`)
  }

  get parameterSpec() {
    return [
      {
        type: 'number',
        name: 'syncWaitCount',
        label: 'sync-wait-count'
      }
    ]
  }

  get taskPrefixes() {
    return ['flow-sync']
  }

  get help() {
    return 'integration/connector/flow-sync-connector'
  }
}

ConnectionManager.registerConnector('flow-sync-connector', new FlowSyncConnector())
