package policy

import (
	"regexp"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/service/iam"
)

// regex for parsing sandstorm-users
var sandstormRegex = regexp.MustCompile(`(^[sS]andstorm-.*|\.tv$)`)

// User represent an aws User
type User struct {
	*iam.User
	Groups []*iam.Group
}

/*ListUsers returns
-all users with prefix /sandstorm-
-all users with policyprefix /sandstorm-{env}
*/
func (pg *IAMPolicyGenerator) ListUsers() ([]*iam.User, error) {
	params := &iam.ListUsersInput{
		MaxItems: aws.Int64(1000),
	}
	var users, newUsers []*iam.User
	var resp *iam.ListUsersOutput
	var err error

	for {
		resp, err = pg.IAM.ListUsers(params)
		if err != nil {
			return nil, err
		}
		newUsers = ParseUsers(resp.Users)

		users = append(users, newUsers...)

		if resp.IsTruncated != nil && *resp.IsTruncated {
			params.Marker = resp.Marker
		} else {
			break
		}

	}
	return users, err

}

// ParseUsers is used when a general ListUsers is called without a PathPrefix to only return sandstorm users
func ParseUsers(inputUsers []*iam.User) []*iam.User {
	var validUsers []*iam.User
	for _, user := range inputUsers {
		if sandstormRegex.MatchString(*user.UserName) {
			validUsers = append(validUsers, user)
		}
	}

	return validUsers
}

/*GetUser does:
-Gets User info
-Gets User's Groups
*/
func (pg *IAMPolicyGenerator) GetUser(username string) (User, error) {
	user := User{}
	input := &iam.GetUserInput{
		UserName: aws.String(username),
	}

	output, err := pg.IAM.GetUser(input)
	if err != nil {
		return user, err
	}
	user.User = output.User

	listGroupsinput := &iam.ListGroupsForUserInput{
		UserName: aws.String(username), // Required
	}

	groups, err := pg.IAM.ListGroupsForUser(listGroupsinput)
	if err != nil {
		return user, err
	}

	user.Groups = groups.Groups
	return user, err
}
