package queue

import (
	"fmt"
	"path/filepath"
	"strings"

	"github.com/gofrs/uuid"
)

const (
	maxQueuePrefixLength   = 42
	maxNamePrefixLength    = 20
	defaultQueueConfigPath = "/var/run/sandstorm/"
	defaultQueueFileName   = "queue_arn"
	defaultQueueNamePrefix = "sandstorm"
	defaultRegion          = "us-west-2"
)

//Config for Queue
type Config struct {
	QueueArn        string
	Region          string
	AccountID       string
	QueueURL        string
	TopicArn        string
	QueueConfigPath string
	QueueFileName   string
	QueueNamePrefix string
	WaitTimeSeconds int
}

func truncatePrefix(prefix string, maxLength int) (truncated string) {
	truncated = prefix
	if len(truncated) > maxLength {
		truncated = truncated[0:maxLength]
	}
	return
}

// buildQueueIdentifier returns a newly generated UUID and a FQDN
// Queuenames have a maximum length of 80 chars and and we prefix with 'sandstorm'
// and suffix wth a UUID. Hostnames are truncated down to 43-len(prefix) chars to fit
// name length
func buildQueueIdentifier(namePrefix, hostname string) (string, error) {
	namePrefix = truncatePrefix(namePrefix, maxNamePrefixLength)
	hostname = truncatePrefix(hostname, maxQueuePrefixLength-len(namePrefix))

	uid, err := uuid.NewV4()
	if err != nil {
		return "", err
	}

	name := strings.Join([]string{namePrefix, hostname, uid.String()}, "-")
	name = strings.Replace(name, ".", "_", -1)
	return name, nil
}

func buildQueueArn(region, accountID, queueName string) string {
	return fmt.Sprintf("arn:aws:sqs:%s:%s:%s", region, accountID, queueName)
}

// DefaultConfig creates a config with default values
func DefaultConfig() Config {
	return Config{
		QueueConfigPath: defaultQueueConfigPath,
		QueueFileName:   defaultQueueFileName,
		QueueNamePrefix: defaultQueueNamePrefix,
		Region:          defaultRegion,
	}
}

// replaces nil values in provided config with defaultConfig
func mergeConfig(provided *Config, defaultConfig Config) {
	if provided.QueueConfigPath == "" {
		provided.QueueConfigPath = defaultConfig.QueueConfigPath
	}

	if provided.QueueFileName == "" {
		provided.QueueFileName = defaultConfig.QueueFileName
	}

	if provided.QueueNamePrefix == "" {
		provided.QueueNamePrefix = defaultConfig.QueueNamePrefix
	}

	if provided.Region == "" {
		provided.Region = defaultConfig.Region
	}
}

// QueueConfigFullPath returns the queue config
func (cfg *Config) QueueConfigFullPath() string {
	return filepath.Join(cfg.QueueConfigPath, cfg.QueueFileName)
}
