package main

import (
	"flag"
	"fmt"
	"strings"

	"github.com/charmbracelet/log"
	"github.com/nicklaw5/helix/v2"
)

// Comma separated strings
type CSStrings []string

func searchHelp() {
	fmt.Print("\nTwitch category commands.  Valid commands are:\n\n")
}

func search(client *helix.Client, args []string) {
	var params = helix.StreamsParams{}

	fs := flag.NewFlagSet("search", flag.ContinueOnError)

	csvValue := func(in string) (s []string) {
		s = strings.Split(in, ",")
		for i := range s {
			s[i] = strings.TrimSpace(s[i])
		}

		return
	}

	langs := fs.String("lang", "en", "Comma separated list of languages (e.g., en,de,etc).")
	games := fs.String("games", "", "List of games to search in. (IDs only for now)")
	streamType := fs.String("type", "all", "Type of videos to return (e.g., all, live, or vodcast)")

	_ = client

	if err := fs.Parse(args); err != nil {
		log.Fatalf("Couldn't parse arguments to search: %v", err)
	}

	params.Language = csvValue(*langs)
	params.GameIDs = csvValue(*games)
	params.Type = *streamType
	log.Infof("Params: %+v", params)

	searchWithParams(client, &params)

	// if len(args) < 1 {
	// 	log.Error("Insufficient arguments.")
	// 	searchHelp()
	// 	return
	// }
}

func searchWithParams(client *helix.Client, params *helix.StreamsParams) {
	resp, err := client.GetStreams(params)
	if err != nil {
		log.Info("Search error: %v", err)
		return
	}

	// Print what we've got
	for _, stream := range resp.Data.Streams {
		fmt.Printf(
			"%v is streaming %v for %v viewers\n",
			stream.UserName,
			stream.GameName,
			stream.ViewerCount,
		)
		fmt.Printf("%v\n\n", stream.Title)
	}
}
