TheMathemagicians/sevenkeys/logic/storage.go

120 lines
2.4 KiB
Go

package logic
import (
"database/sql"
"io"
"os"
"os/exec"
"sevenkeys/database"
"strings"
)
func CreateStorageArea(db *sql.DB, storageArea database.StorageArea) error {
// TODO: Check if there's already a storage are with the same name
// TODO: Check if the type entered is valid
err := database.InsertStorageArea(db, storageArea)
if err != nil {
return err
}
return nil
}
func SelectStorageArea(db *sql.DB) (database.StorageArea, error) {
var selectedStorageArea database.StorageArea
storageAreas, err := database.GetAllStorageAreas(db)
if err != nil {
return selectedStorageArea, err
}
cmd := exec.Command("fzf")
cmd.Stderr = os.Stderr
fzfStdin, err := cmd.StdinPipe()
if err != nil {
return selectedStorageArea, err
}
go func() {
defer fzfStdin.Close()
for _, area := range storageAreas {
io.WriteString(fzfStdin, area.Name+"\n")
}
}()
fzfOutput, err := cmd.Output()
if err != nil {
return selectedStorageArea, err
}
key := strings.TrimSuffix(string(fzfOutput), "\n")
for _, area := range storageAreas {
if area.Name == key {
selectedStorageArea = area
break
}
}
return selectedStorageArea, nil
}
func StoreAfterLastCard(db *sql.DB, cardLocation database.CardLocation) error {
lastPosition, err := database.GetLastPositionInStorageArea(db, cardLocation.StorageAreaId)
if err != nil {
return err
}
cardLocation.Position = lastPosition + 1
err = database.InsertCardLocation(db, cardLocation)
if err != nil {
return err
}
return nil
}
func StoreInEmptySlot(db *sql.DB, cardLocation database.CardLocation, cardLocationId int) error {
cardLocation.Id = cardLocationId
err := database.InsertCardInExistingLocation(db, cardLocation)
if err != nil {
return err
}
return nil
}
func StoreCard(db *sql.DB, cardLocation database.CardLocation) error {
storageAreaType, err := database.GetStorageAreaTypeById(db, cardLocation.StorageAreaId)
if err != nil {
return err
}
if storageAreaType == database.StorageAreaTypeBinder {
nextEmptySlotId, err := database.GetNextEmptySlotInBinder(db, cardLocation.StorageAreaId)
if err == sql.ErrNoRows {
err = StoreAfterLastCard(db, cardLocation)
if err != nil {
return err
}
} else if err != nil {
return err
} else {
err = StoreInEmptySlot(db, cardLocation, nextEmptySlotId)
if err != nil {
return err
}
}
return nil
}
err = StoreAfterLastCard(db, cardLocation)
if err != nil {
return err
}
return nil
}