package mpris

import (
	"fmt"
	"io"
	"net/http"
	"os"
	"strings"

	"github.com/Endg4meZer0/go-mpris"
	"github.com/godbus/dbus/v5"
)

type PlayerInfo struct {
	Name    string
	Title   string
	Artist  []string
	Album   string
	ArtURL  string
}

func Mpris() ([]PlayerInfo, error) {
	conn, err := dbus.SessionBus()
	if err != nil {
		return nil, err
	}

	names, err := mpris.List(conn)
	if err != nil {
		return nil, err
	}
	if len(names) == 0 {
		return nil, fmt.Errorf("no MPRIS players found")
	}

	var players []PlayerInfo
	for _, name := range names {
		player := mpris.New(conn, name)

		metadata, err := player.GetMetadata()
		if err != nil {
			return nil, err
		}

		title, _ := metadata["xesam:title"].Value().(string)
		artist, _ := metadata["xesam:artist"].Value().([]string)
		album, _ := metadata["xesam:album"].Value().(string)

		var artURL string
		if val, ok := metadata["mpris:artUrl"]; ok {
			if url, ok := val.Value().(string); ok {
				artURL = url
			}
		}

		players = append(players, PlayerInfo{
			Name:   name,
			Title:  title,
			Artist: artist,
			Album:  album,
			ArtURL: artURL,
		})
	}

	return players, nil
}

func IsRemoteArt(uri string) bool {
	return strings.HasPrefix(uri, "http://") || strings.HasPrefix(uri, "https://")
}

func DownloadArt(url, dest string) error {
	resp, err := http.Get(url)
	if err != nil {
		return fmt.Errorf("failed to fetch art: %w", err)
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		return fmt.Errorf("bad status: %s", resp.Status)
	}

	out, err := os.Create(dest)
	if err != nil {
		return fmt.Errorf("failed to create file: %w", err)
	}
	defer out.Close()

	_, err = io.Copy(out, resp.Body)
	if err != nil {
		return fmt.Errorf("failed to save art: %w", err)
	}

	return nil
}
