package cmd

import (
	"bufio"
	"fmt"
	"os/exec"
	"strings"

	"github.com/spf13/cobra"
)

var updateCmd = &cobra.Command{
	Use:   "update",
	Short: "Fetch items for a source and update it",
	Long: `Fetch items from a feed source using the configured "fetch" action.
Items returned by a successful fetch will be used to update the source.
No changes will be made to the source if the fetch does not succeed.`,
	Run: func(cmd *cobra.Command, args []string) {
		update()
	},
}

var source string
var dryRun bool

func init() {
	rootCmd.AddCommand(updateCmd)

	updateCmd.Flags().StringVarP(&source, "source", "s", "", "Source name to fetch (required)")
	updateCmd.MarkFlagRequired("source")

	updateCmd.Flags().BoolVar(&dryRun, "dry-run", false, "Instead of updating the source, print the fetched items")
}

func update() {
	fmt.Printf("Hello %s\n", source)

	if dryRun {
		return
	}

	cmd := exec.Command("sh", "-c", "echo Wout; sleep 1; echo 1>&2 Werr; sleep 1; echo Wout2; sleep 1; echo 1>&2 Werr2")
	stdout, _ := cmd.StdoutPipe()
	stderr, _ := cmd.StderrPipe()

	cout := make(chan int)
	go func() {
		scanout := bufio.NewScanner(stdout)
		for scanout.Scan() {
			text := strings.TrimSpace(scanout.Text())
			fmt.Printf("[stdout] %s\n", text)
		}
		cout <- 1
	}()

	cerr := make(chan int)
	go func() {
		scanerr := bufio.NewScanner(stderr)
		for scanerr.Scan() {
			text := strings.TrimSpace(scanerr.Text())
			fmt.Printf("[stderr] %s\n", text)
		}
		cerr <- 1
	}()

	cmd.Start()
	<-cout
	<-cerr
}