require 'json'
require 'rest-assured'
require 'process-helper'
require 'aws-sdk'

Before do
  executable_args = ['localstack', 'start']
  wait_for = /(Ready\.)/
  @process = ProcessHelper::ProcessHelper.new({print_lines: false})
  @process.start(executable_args, wait_for, 30)

  @sqs_client = create_sqs_client()
  @queue = create_queue(@sqs_client, 'my-test-queue')


  @sns_client = create_sns_client()
  @topic = create_topic(@sns_client, 'my-test-topic')

  @subscribed_queue = create_queue(@sqs_client, 'my-subscribed-queue')
  queue_arn = get_queue_arn(@sqs_client, @subscribed_queue)
  subscribe_queue_to_topic(queue_arn, @sns_client, @topic.topic_arn)
end

After do
  puts 'CLEAN UP'
  if @process
    `docker kill localstack_main`
  end
end

def create_sns_client()
  Aws::SNS::Client.new(
      endpoint: 'http://localhost:4575',
      region: 'eu-west-1'
  )
end

def create_topic(client, topic_name)
  begin
    client.create_topic({
                            name: topic_name, # required
                            tags: [
                                {
                                    key: "created", # required
                                    value: "by localstack", # required
                                },
                            ],
                        })
  rescue Seahorse::Client::NetworkingError => e
    puts(e.message)
  end
end

def subscribe_queue_to_topic(queue_arn, topic_client, topic_arn)
  topic_client.subscribe({
                             topic_arn: topic_arn, # required
                             protocol: 'sqs', # required
                             endpoint: queue_arn,
                             return_subscription_arn: true,
                         })
end

def get_queue_arn(sqs_client, queue)
  resp = sqs_client.get_queue_attributes({
                                             queue_url: queue.queue_url,
                                             attribute_names: ['QueueArn']
                                         })
  resp.attributes["QueueArn"]
end

def create_sqs_client()
  begin
    Aws::SQS::Client.new(
        endpoint: 'http://localhost:4576',
        region: 'eu-west-1'
    )
  rescue Seahorse::Client::NetworkingError => e
    puts(e.message)
  end

end

def create_queue(sqs_client, queue_name)
  begin
    sqs_client.create_queue({queue_name: queue_name,
                             attributes: {
                                 "ReceiveMessageWaitTimeSeconds" => "20"
                             }})
  rescue Seahorse::Client::NetworkingError => e
    puts(e.message)
  end
end

