2023-09-14 14:52:04 +07:00
|
|
|
package data
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"encoding/json"
|
|
|
|
|
"log"
|
|
|
|
|
"os"
|
2023-10-03 15:06:50 +07:00
|
|
|
"path/filepath"
|
2023-09-21 17:28:37 +07:00
|
|
|
"recipe-manager/models"
|
2023-10-03 15:06:50 +07:00
|
|
|
"sort"
|
2023-09-14 14:52:04 +07:00
|
|
|
)
|
|
|
|
|
|
2023-10-03 15:06:50 +07:00
|
|
|
func readFile(version string) *models.Recipe {
|
|
|
|
|
path := filepath.Join("cofffeemachineConfig", version)
|
|
|
|
|
file, err := os.Open(path)
|
2023-09-14 14:52:04 +07:00
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
log.Fatalf("Error when open file: %s", err)
|
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
defer file.Close()
|
|
|
|
|
|
2023-09-21 17:28:37 +07:00
|
|
|
var data *models.Recipe
|
2023-09-14 14:52:04 +07:00
|
|
|
|
|
|
|
|
err = json.NewDecoder(file).Decode(&data)
|
|
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
log.Fatalf("Error when decode file: %s", err)
|
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return data
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
type Data struct {
|
2023-10-03 15:06:50 +07:00
|
|
|
CurrentVersion string
|
|
|
|
|
AllVersions []string
|
|
|
|
|
recipe *models.Recipe
|
2023-09-14 14:52:04 +07:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func NewData() *Data {
|
2023-10-03 15:06:50 +07:00
|
|
|
|
|
|
|
|
files, err := filepath.Glob("cofffeemachineConfig/coffeethai02_*.json")
|
|
|
|
|
if err != nil {
|
|
|
|
|
log.Panic("Error when scan recipe files:", err)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
sort.Slice(files, func(i, j int) bool {
|
|
|
|
|
file1, err := os.Stat(files[i])
|
|
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
log.Panic("Error when get file info:", err)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
file2, err := os.Stat(files[j])
|
|
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
log.Panic("Error when get file info:", err)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return file1.ModTime().After(file2.ModTime())
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
for i := 0; i < len(files); i++ {
|
|
|
|
|
files[i] = filepath.Base(files[i])
|
|
|
|
|
}
|
|
|
|
|
|
2023-09-14 14:52:04 +07:00
|
|
|
return &Data{
|
2023-10-03 15:06:50 +07:00
|
|
|
CurrentVersion: "coffeethai02_580.json",
|
|
|
|
|
AllVersions: files,
|
|
|
|
|
recipe: readFile("coffeethai02_580.json"),
|
2023-09-14 14:52:04 +07:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2023-10-03 15:06:50 +07:00
|
|
|
func (d *Data) GetRecipe(version string) models.Recipe {
|
|
|
|
|
|
|
|
|
|
if version == "" || version == d.CurrentVersion {
|
|
|
|
|
return *d.recipe
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
log.Println("Change recipe to version:", version)
|
|
|
|
|
|
|
|
|
|
// change current version and read new recipe
|
|
|
|
|
d.CurrentVersion = version
|
|
|
|
|
d.recipe = readFile(version)
|
2023-09-25 15:29:42 +07:00
|
|
|
return *d.recipe
|
2023-09-14 14:52:04 +07:00
|
|
|
}
|
|
|
|
|
|
2023-09-21 17:28:37 +07:00
|
|
|
func (d *Data) GetRecipe01() []models.Recipe01 {
|
|
|
|
|
return d.recipe.Recipe01
|
2023-09-14 14:52:04 +07:00
|
|
|
}
|