package main

import (
	// "bufio"
	"fmt"
	"log"
	"os/exec"
	"time"
)

func slideshow(ch <-chan string) {
	dir := <-ch
	ticker := time.NewTicker(time.Duration(config.Duration) * time.Minute)

	//set a flat background color based on config defaults
	fillCmd := exec.Command("swaybg", "-c", "#232136")
	// stdout, _ := fillCmd.StdoutPipe()
	// scanner := bufio.NewScanner(stdout)
	// out := make(chan string)
	// go func() {
	// 	for scanner.Scan() {
	// 		fmt.Println("scanner: ", scanner.Text())
	// 		out <- scanner.Text()
	// 	}
	// }()

	ready := make(chan bool)
	go func() {
		err := fillCmd.Start()
		if err != nil {
			fmt.Println("could not set background color", err)
		}
		//NOTE: this is *very* hacky, but it is difficult to know when swaybg has initiated
		time.Sleep(100 * time.Millisecond)
		ready <- true
		fmt.Println("bg color set!")
		fillCmd.Wait()
	}()

	var cmd *exec.Cmd
	go func() {
		for {
			<-ready
			newCmd := setRandomWallpaper(dir)
			if cmd != nil {
				err := cmd.Process.Kill()
				if err != nil {
					log.Fatal("could not kill process", err)
				}
			}
			cmd = newCmd
			select {
			case dir = <-ch:
				log.Println("directory set!")
				continue
			case <-ticker.C:
				continue
			}
		}
	}()
}

func setRandomWallpaper(dir string) *exec.Cmd {
	img, err := pickRandomImage(dir)
	if err != nil {
		panic(err)
	}

	cmd := exec.Command("swaybg", "-i", img, "--mode", "fit")
	fmt.Printf("setting wallpaper: %v\n", img)
	err = cmd.Start()
	if err != nil {
		log.Fatal("failed to set wallpaper!", err)
	}
	go cmd.Wait()
	return cmd
}
