package main

import (
	"log"
	"fmt"
)

func (app *application) SetupCrons() {
	app.pb.Cron().MustAdd("update_sets_and_cards", "0 3 * * *", func() {
		log.Println("Started updating sets and cards...")
		
		scryfallSets := fetchApiSets()

		insertQuery := CreateBulkSetsInsertQuery(scryfallSets)
		_, err := app.pb.DB().
						NewQuery(insertQuery).
						Execute()
		if err != nil {
			log.Println(fmt.Sprintf("[ERROR] %v",err))
		}
		log.Println(fmt.Sprintf("Updated %d sets", len(scryfallSets)))

		setsCodesQuery := []MtgSet{}
		err = app.pb.DB().
				NewQuery("SELECT id, code FROM mtg_set").
				All(&setsCodesQuery)
		if err != nil {
			log.Println(fmt.Sprintf("[ERROR] %v",err))
		}

		setsCodes := map[string]string{}
		for _,v := range setsCodesQuery {
			setsCodes[v.ID] = v.Code
		}

		selectedSets := []Brawlset{}
		selectedSetsCodes := []string{}
		err = app.pb.DB().
				NewQuery("SELECT sets FROM brawlset").
				All(&selectedSets)
		if err != nil {
			log.Println(fmt.Sprintf("[ERROR] %v",err))
		}
		for _, v := range selectedSets {
			for _, set := range v.Sets {
				selectedSetsCodes = append(selectedSetsCodes, setsCodes[set])
			}
		}

		log.Println(fmt.Sprintf("Fetching %d sets...", len(selectedSetsCodes)))
		allCards := []ScryfallCard{}
		for _, v := range selectedSetsCodes {
			url := "https://api.scryfall.com/cards/search?q=(game%3Apaper)+set%3A" + v
			allCards = fetchApiCards(url, allCards)
		}

		upsertQuery := CreateBulkCardsUpsertQuery(allCards)
		_, err = app.pb.DB().
						NewQuery(upsertQuery).
						Execute()
		if err != nil {
			log.Println(fmt.Sprintf("[ERROR] %v",err))
		}
		log.Println(fmt.Sprintf("Updated %d cards", len(allCards)))
	})

	app.pb.Cron().MustAdd("regenerate_cache_json", "30 3 * * *", func() {
		GenerateCache(app.pb.App)
	})
}
