package repolist

import (
	"fmt"
	"os"
	"time"

	"go.wit.com/log"
)

// scan repos every i seconds
// check every 'delay seconds for the checkbox changing
// this logic is unintuitive because I want it to fluidly
// never tricker quickly but also want to print something
// out that the app is alive since, technically
// the GUI is *NOT* this app and could be alive when
// the application is actually stalled somewhere
// plus these things are fun for me and a distraction when
// I've been working 50 days in a row on this gui code

// this also means that if you click the checkbox after
// the delay, then the scan will run right away, but if
// you check the checkbox twice in 5 seconds, it won't
// rerun until the delay again
func (r *RepoList) Watchdog(f func()) {
	var delay int = 99
	var i int = delay
	MyTicker(1*time.Second, "newScan()", func() {
		i += 1
		// check if the env var is set to autoscan
		if os.Getenv("REPO_AUTO_SCAN") != "true" {
			if i < delay {
				i = delay
			}
			// print every 'delay' seconds
			if i%delay == 0 {
				log.Log(REPOWARN, "Not auto scanning", i, "REPO_AUTO_SCAN =", os.Getenv("REPO_AUTO_SCAN"))
			}
			return
		}
		if i < delay {
			return
		}
		i = 0
		r.ScanRepositories()
		f()
	})
}

// timeFunction takes a function as an argument and returns the execution time.
func TimeFunction(f func()) time.Duration {
	startTime := time.Now()      // Record the start time
	f()                          // Execute the function
	return time.Since(startTime) // Calculate the elapsed time
}

func MyTicker(t time.Duration, name string, f func()) {
	ticker := time.NewTicker(t)
	defer ticker.Stop()
	done := make(chan bool)
	/*
		go func() {
			time.Sleep(10 * time.Second)
			done <- true
		}()
	*/
	for {
		select {
		case <-done:
			fmt.Println("Done!")
			return
		case t := <-ticker.C:
			log.Verbose(name, "Current time: ", t)
			f()
		}
	}
}