import {
  SQSClient,
  SendMessageCommand,
  DeleteMessageCommand,
  ReceiveMessageCommand
} from '@aws-sdk/client-sqs'
import { PlatformConfig, ContainerDeploymentRequest } from 'types'
import { AwsCredentialsClient } from 'aws-credentials-client'
import { logInfo, logError, logDebug } from 'log'

export class DeploymentQueueClient {

  static sendDeploymentRequest(platformConfig: PlatformConfig, deploymentRequest: ContainerDeploymentRequest) {
    logInfo({ message: '[DeploymentQueueClient] Starting deployment sequence' })
    return DeploymentQueueClient.createAwsSqsClient(platformConfig)
      .then(sqsClient => {

        const sendMessageParams = {
          QueueUrl: platformConfig.awsDeploymentSqsArn,
          MessageBody: JSON.stringify(deploymentRequest)
        }

        logDebug({ message: '[DeploymentQueueClient] SendMessageCommand params', data: sendMessageParams })
        const command = new SendMessageCommand(sendMessageParams)

        return sqsClient.send(command)
          .then(() => logInfo({ message: '[DeploymentQueueClient] Deployment request sent' }))
          .catch(error => logError({ message: '[DeploymentQueueClient] Could not send deployment request', error }))
      })

  }

  static pollForDeploymentRequests(platformConfig: PlatformConfig, handleDeploymentRequest: (deploymentRequest: ContainerDeploymentRequest) => Promise<void>) {
    logInfo({ message: '[DeploymentQueueClient] Starting polling for deployment requests' })
    DeploymentQueueClient.createAwsSqsClient(platformConfig).then(sqsClient => {
      const FIVE_MINUTES = 3000

      setInterval(() => {

        const receiveMessageCommand = new ReceiveMessageCommand({ QueueUrl: platformConfig.awsDeploymentSqsArn })

        sqsClient.send(receiveMessageCommand)
          .then(data => data.Messages.map(message => {

            logInfo({ message: '[DeploymentQueueClient] Received deployment request' })

            handleDeploymentRequest(JSON.parse(message.Body))
              .then(() => {

                const deleteMessageCommand = new DeleteMessageCommand({
                  QueueUrl: platformConfig.awsDeploymentSqsArn,
                  ReceiptHandle: message.ReceiptHandle
                })

                sqsClient.send(deleteMessageCommand)
                  .then(() => logInfo({ message: '[DeploymentQueueClient] Removing deployment request from queue' }))
                  .catch(error => logError({ message: '[DeploymentQueueClient] Could not delete message from queue', error }))
              })

          }))
          .catch(error => logError({ message: '[ContainerManagerServer] Could not handle incoming deployment request', error }))
      }, FIVE_MINUTES)

      })
  }

  static createAwsSqsClient(platformConfig: PlatformConfig) {
    return AwsCredentialsClient.resolveAwsCredentials(platformConfig)
      .then(awsCredentials => new SQSClient({
        region: platformConfig.awsRegion,
        credentials: awsCredentials
      }))
  }

}
