108 lines
2.7 KiB
Go
108 lines
2.7 KiB
Go
package mailq
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
"sort"
|
|
)
|
|
|
|
type QSortConfig struct {
|
|
attributes []qEntryAttributeSortConfig
|
|
}
|
|
|
|
type qEntryAttributeSortConfig struct {
|
|
attribute string
|
|
order string
|
|
}
|
|
|
|
func NewSortConfig() QSortConfig {
|
|
return QSortConfig{}
|
|
}
|
|
|
|
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 QSortConfig) By(attributeName string, order string) (QSortConfig, error) {
|
|
if !isQEntryAttribute(attributeName) {
|
|
return c, errors.New(fmt.Sprintf("Invalid sort attribute: '%s' given!", attributeName))
|
|
}
|
|
if order != "ASC" && order != "DESC" {
|
|
return c, errors.New(fmt.Sprintf("Invalid sort order '%s' given!", order))
|
|
}
|
|
newAttributeConfig := qEntryAttributeSortConfig{attribute: attributeName, order: order}
|
|
c.attributes = append(c.attributes, newAttributeConfig)
|
|
return c, nil
|
|
}
|
|
|
|
func (queue MailQ) Sort(config QSortConfig) {
|
|
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
|
|
})
|
|
}
|