TheMathemagicians/sevenkeys/logic/search.go

67 lines
1.4 KiB
Go
Raw Normal View History

2024-05-30 14:19:31 +00:00
package logic
import (
"database/sql"
"fmt"
"io"
"os"
"os/exec"
2024-05-30 14:19:31 +00:00
"sevenkeys/database"
"strings"
2024-05-30 14:19:31 +00:00
)
// The SearchOptions type is a map of `string` keys (which can be searched using fzf)
// to `string` values (which represent a primary key in the CardPrintings table)
type SearchOptions map[string]string
2024-05-30 14:19:31 +00:00
func GetAllSearchOptions(db *sql.DB) (SearchOptions, error) {
var searchOptions SearchOptions = make(map[string]string)
2024-05-30 14:19:31 +00:00
cardPrintings, err := database.GetAllCardPrintings(db)
if err != nil {
return searchOptions, err
}
for _, printing := range cardPrintings {
searchString := fmt.Sprintf("%s (%s %s) [%s]", printing.Name, printing.SetCode, printing.CollectorNumber, printing.Language)
if printing.IsFoil {
searchString += " FOIL"
}
if printing.IsPromo {
searchString += " PROMO"
}
searchOptions[searchString] = printing.Id
}
return searchOptions, err
}
func Search(searchOptions SearchOptions) (string, string, error) {
cmd := exec.Command("fzf")
cmd.Stderr = os.Stderr
fzfStdin, err := cmd.StdinPipe()
if err != nil {
return "", "", err
}
go func() {
defer fzfStdin.Close()
for searchString, _ := range searchOptions {
io.WriteString(fzfStdin, searchString+"\n")
}
}()
fzfOutput, err := cmd.Output()
if err != nil {
return "", "", err
}
key := strings.TrimSuffix(string(fzfOutput), "\n")
return searchOptions[key], key, nil
}