package legacyperm

import (
	"sort"
	"strings"

	"code.justin.tv/beefcake/server/rpc/beefcake"
	"github.com/aws/aws-sdk-go/service/dynamodb"
	"github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute"
)

// Roles represents a set of users
type Roles []*beefcake.LegacyPermission_Role

func (u Roles) Len() int { return len(u) }
func (u Roles) Less(i, j int) bool {
	return strings.Compare(u[i].GetId(), u[j].GetId()) < 0
}
func (u Roles) Swap(i, j int) { u[i], u[j] = u[j], u[i] }

// MarshalDynamoDBAttributeValue implements dynamodbattribute.Marshaller
func (u Roles) MarshalDynamoDBAttributeValue(av *dynamodb.AttributeValue) error {
	if len(u) == 0 {
		av.SetM(map[string]*dynamodb.AttributeValue{})
		return nil
	}

	out := make(map[string]Role, len(u))
	for _, item := range u {
		out[item.GetId()] = Role(*item)
	}

	res, err := dynamodbattribute.Marshal(out)
	if err != nil {
		return err
	}

	*av = *res
	return nil
}

// UnmarshalDynamoDBAttributeValue implements dynamodbattribute.Unmarshaller
func (u *Roles) UnmarshalDynamoDBAttributeValue(av *dynamodb.AttributeValue) error {
	var out map[string]Role

	if err := dynamodbattribute.Unmarshal(av, &out); err != nil {
		return err
	}

	users := make([]*beefcake.LegacyPermission_Role, 0, len(out))
	for _, roleUser := range out {
		br := beefcake.LegacyPermission_Role(roleUser)
		users = append(users, &br)
	}

	*u = Roles(users)
	sort.Sort(u)

	return nil
}
