67 lines
1.3 KiB
Go
67 lines
1.3 KiB
Go
package logic
|
|
|
|
import (
|
|
"database/sql"
|
|
"fmt"
|
|
"io"
|
|
"os"
|
|
"os/exec"
|
|
"sevenkeys/database"
|
|
"strings"
|
|
)
|
|
|
|
// The SearchOptions type is a map of `string`s (which can be searched using fzf)
|
|
// to `int`s (which represent a primary key in the CardPrintings table)
|
|
type SearchOptions map[string]int
|
|
|
|
func GetAllSearchOptions(db *sql.DB) (SearchOptions, error) {
|
|
var searchOptions SearchOptions = make(map[string]int)
|
|
|
|
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) (int, string, error) {
|
|
cmd := exec.Command("fzf")
|
|
cmd.Stderr = os.Stderr
|
|
|
|
fzfStdin, err := cmd.StdinPipe()
|
|
if err != nil {
|
|
return -1, "", err
|
|
}
|
|
|
|
go func() {
|
|
defer fzfStdin.Close()
|
|
for searchString, _ := range searchOptions {
|
|
io.WriteString(fzfStdin, searchString+"\n")
|
|
}
|
|
}()
|
|
|
|
fzfOutput, err := cmd.Output()
|
|
if err != nil {
|
|
return -1, "", err
|
|
}
|
|
|
|
key := strings.TrimSuffix(string(fzfOutput), "\n")
|
|
|
|
return searchOptions[key], key, nil
|
|
}
|