Passed
Pull Request — main (#42)
by Yume
01:18
created

models.DeckStatus.ToString   A

Complexity

Conditions 5

Size

Total Lines 10
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 10
nop 0
dl 0
loc 10
rs 9.3333
c 0
b 0
f 0
1
package models
2
3
import (
4
	"github.com/memnix/memnixrest/pkg/database"
5
	"github.com/memnix/memnixrest/pkg/utils"
6
	"gorm.io/gorm"
7
	"math/rand"
8
	"strconv"
9
	"time"
10
)
11
12
// Deck structure
13
type Deck struct {
14
	gorm.Model  `swaggerignore:"true"`
15
	Share       bool       `json:"deck_share" example:"true" gorm:"default:false"`
16
	Status      DeckStatus `json:"deck_status" example:"2"` // 1: Draft - 2: Private - 3: Published
17
	DeckName    string     `json:"deck_name" example:"First Deck"`
18
	Description string     `json:"deck_description" example:"A simple demo deck"`
19
	Banner      string     `json:"deck_banner" example:"A banner url"`
20
	Key         string     `json:"deck_key" example:"MEM"`
21
	Code        string     `json:"deck_code" example:"6452"`
22
	Lang        string     `json:"deck_lang"`
23
}
24
25
// DeckStatus enum type
26
type DeckStatus uint8
27
28
const (
29
	DeckPrivate DeckStatus = iota + 1
30
	DeckWaitingReview
31
	DeckPublic
32
)
33
34
// ToString returns DeckStatus value as a string
35
func (s DeckStatus) ToString() string {
36
	switch s {
37
	case DeckWaitingReview:
38
		return "Deck Waiting Review"
39
	case DeckPrivate:
40
		return "Deck Private"
41
	case DeckPublic:
42
		return "Deck Public"
43
	default:
44
		return "Unknown"
45
	}
46
}
47
48
// NotValidate performs validation of the deck
49
func (deck *Deck) NotValidate() bool {
50
	return len(deck.DeckName) < utils.MinDeckLen || len(deck.DeckName) > utils.MaxDeckNameLen || len(deck.Description) < utils.MinDeckLen || len(
51
		deck.Description) > utils.MaxDefaultLen || len(deck.Banner) > utils.MaxImageURLLen || len(deck.Key) > utils.DeckKeyLen || len(
52
		deck.Lang) > utils.MaxLangLen
53
}
54
55
// GenerateCode creates a random code from the deck key
56
func (deck *Deck) GenerateCode() {
57
	rand.Seed(time.Now().UTC().UnixNano())
58
59
	randomInt := rand.Intn(99)
60
	runes := []rune(deck.Key)
61
	var result []int
62
	result = append(result, randomInt)
63
64
	for i := 0; i < len(runes); i++ {
65
		result = append(result, int(runes[i]))
66
	}
67
68
	rand.Shuffle(len(result), func(i, j int) { result[i], result[j] = result[j], result[i] })
69
70
	deck.Code = strconv.Itoa(result[0]+result[1]/2) + strconv.Itoa(result[4]) + strconv.Itoa(result[2]+result[3]/2)
71
}
72
73
// GetOwner returns the deck Owner
74
func (deck *Deck) GetOwner() User {
75
	db := database.DBConn
76
77
	access := new(Access)
78
79
	if err := db.Joins("User").Joins("Deck").Where("accesses.deck_id =? AND accesses.permission >= ?", deck.ID, AccessOwner).Find(&access).Error; err != nil {
80
		return access.User
81
	}
82
83
	return access.User
84
}
85