package cmd

import (
	"encoding/json"
	"fmt"
	"os"
	"time"

	"git.sr.ht/~timharek/yr/cmd/internal/ui/table"
	"git.sr.ht/~timharek/yr/pkg/browser"
	"git.sr.ht/~timharek/yr/yr"
	"github.com/spf13/cobra"
)

var tomorrowCmd = &cobra.Command{
	Use:     "tomorrow <location>",
	Aliases: []string{"twm", "trm"},
	Short:   "Tomorrow's forecasted weather",
	Args:    cobra.MaximumNArgs(1),
	Run:     tomorrow,
}

func init() {
	rootCmd.AddCommand(tomorrowCmd)
}

func tomorrow(cmd *cobra.Command, args []string) {
	f := forecastHelper(args)

	if isWeb {
		url := fmt.Sprintf("https://www.yr.no/en/forecast/hourly-table/%.4f,%.4f?i=1", f.Coordinates.Latitude, f.Coordinates.Longitude)
		err := browser.OpenURL(url)
		if err != nil {
			cobra.CheckErr(err)
		}
		os.Exit(0)
	}

	t := table.New()

	tomorrows := []yr.Forecast{}

	tomorrow := time.Now().AddDate(0, 0, 1)
	for _, item := range f.Forecast {
		if item.Time.Format(time.DateOnly) != tomorrow.Format(time.DateOnly) {
			continue
		}
		if !isUTC {
			item.Time = item.Time.Local()
		}
		tomorrows = append(tomorrows, item)
		t.Row(
			fmt.Sprintf("tomorrow %s", item.Time.Format("15:04")),
			fmt.Sprintf("%.1f °C", item.Temperature),
			fmt.Sprintf("%.1f mm", item.Percipitation),
			fmt.Sprintf("%.1f m/s %s", item.Wind.Speed, item.Wind.DirectionToString()),
		)
	}

	if isJson {
		j, err := json.MarshalIndent(tomorrows, "", "  ")
		cobra.CheckErr(err)
		fmt.Printf("%s", j)
		return
	}

	fmt.Println(t)
}