mailq-inspector/mailq/sorting.go

107 lines
2.6 KiB
Go

package mailq
import (
"fmt"
"sort"
)
type qEntrySortConfig struct {
attributes []qEntryAttributeSortConfig
}
type qEntryAttributeSortConfig struct {
attribute string
order string
}
func NewSortConfig() qEntrySortConfig {
return qEntrySortConfig{}
}
func isQEntryAttribute(attributeName string) bool {
var isValidAttribute bool
switch attributeName {
case "Id", "Status", "Date", "Size", "Sender", "Recipients", "Reason":
isValidAttribute = true
default:
isValidAttribute = false
}
return isValidAttribute
}
func (c qEntrySortConfig) By(attributeName string, order string) qEntrySortConfig {
if !isQEntryAttribute(attributeName) {
panic(fmt.Sprintf("Invalid sort attribute: '%s' given!", attributeName))
}
if order != "ASC" && order != "DESC" {
panic(fmt.Sprintf("Invalid sort order '%s' given!", order))
}
newAttributeConfig := qEntryAttributeSortConfig{attribute: attributeName, order: order}
c.attributes = append(c.attributes, newAttributeConfig)
return c
}
func (queue MailQ) Sort(config qEntrySortConfig) {
if len(config.attributes) == 0 {
return
}
sort.Slice(queue.Entries, func(a int, b int) bool {
for _, sortBy := range config.attributes {
var cmp bool
var skip bool
// Not sure if these are necessary yet
cmp = false
skip = false
switch sortBy.attribute {
case "Id":
if queue.Entries[a].Id == queue.Entries[b].Id {
skip = true
}
cmp = queue.Entries[a].Id < queue.Entries[b].Id
case "Status":
if queue.Entries[a].Status == queue.Entries[b].Status {
skip = true
}
cmp = queue.Entries[a].Status < queue.Entries[b].Status
case "Date":
if queue.Entries[a].Date.Equal(queue.Entries[b].Date) {
skip = true
}
cmp = queue.Entries[a].Date.Before(queue.Entries[b].Date)
case "Size":
if queue.Entries[a].Size == queue.Entries[b].Size {
skip = true
}
cmp = queue.Entries[a].Size < queue.Entries[b].Size
case "Sender":
if queue.Entries[a].Sender == queue.Entries[b].Sender {
skip = true
}
cmp = queue.Entries[a].Sender < queue.Entries[b].Sender
case "Recipients":
if len(queue.Entries[a].Recipients) == len(queue.Entries[b].Recipients) {
skip = true
}
cmp = len(queue.Entries[a].Recipients) < len(queue.Entries[b].Recipients)
case "Reason":
if queue.Entries[a].Reason == queue.Entries[b].Reason {
skip = true
}
cmp = queue.Entries[a].Reason < queue.Entries[b].Reason
default:
// TODO: Handle this error case?
}
if skip == true {
continue
} else {
if sortBy.order == "ASC" {
return cmp
} else if sortBy.order == "DESC" {
return !cmp
}
}
}
return false
})
}