package main

import (
	"encoding/json"
	"io/ioutil"
	"log"
	"os"
	"path/filepath"
	"strconv"
)

type recipe struct {
	Title    string
	Portions int
	Url      string
	Steps    []struct {
		Text        string
		Ingredients []struct {
			Type   string
			Amount any
		}
	}
}

func getRecipeText(id string) ([]byte, error) {
	var b []byte
	textpath := filepath.Join(config.Data, "recipes", id, "text")
	b, err := ioutil.ReadFile(textpath)
	if err != nil {
		return b, err
	}
	return b, nil
}

func getRecipe(id string) (recipe, error) {
	r := recipe{}

	data, err := getRecipeText(id)
	if err != nil {
		return r, err
	}

	err = json.Unmarshal(data, &r)
	if err != nil {
		return r, err
	}

	return r, nil
}

type recipeList []struct {
	Id    string
	Title string
}

func (a recipeList) Len()          int  { return len(a) }
func (a recipeList) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
func (a recipeList) Less(i, j int) bool { return a[i].Title < a[j].Title }

func getRecipeList() recipeList {
	recipes := make(recipeList, 0)

	path := filepath.Join(config.Data, "recipes")
	entries, err := os.ReadDir(path)
	if err == nil {
		for _, v := range entries {
			if v.IsDir() == false {
				continue
			}

			_, err = strconv.Atoi(v.Name())
			if err != nil {
				continue
			}

			textpath := filepath.Join(config.Data, "recipes", v.Name(), "text")
			data, err := ioutil.ReadFile(textpath)
			if err != nil {
				continue
			}

			r := recipe{}
			err = json.Unmarshal(data, &r)
			if err != nil {
				continue
			}

			recipes = append(recipes, struct {
				Id    string
				Title string
			}{v.Name(), r.Title})
		}
	} else {
		log.Printf("Could not read directory '%s'\n", path)
	}

	return recipes
}