package music

import (
				"regexp"
				"strings"
				"time"
)

type (
				Artist struct {
								Name string;
								Website string;
				}

				Album struct {
								Id string;
								Title string;
								Type string;
								ReleaseDate time.Time;
								Artwork string;
								Buyname string;
								Buylink string;
								Links []AlbumLink;
								Description string;
								Credits []AlbumCredit;
								Lyrics string;
				}

				AlbumLink struct {
								Name string;
								Url string;
				}

				AlbumCredit struct {
								Artist *Artist;
								Role string;
				}
)

func (album Album) GetUniqueArtists() []Artist {
				if len(album.Credits) == 1 {
								return []Artist{ *album.Credits[0].Artist }
				}

				// create a map of artists to prevent duplicates
				res := []Artist{}
				for _, credit := range album.Credits {
								artist := *credit.Artist
								exists := false
								for _, c := range res {
												if c == *credit.Artist {
																exists = true
																break
												}
								}
								if exists {
												continue
								}
								res = append(res, artist)
				}

				// now create the actual array to send
				return res
}

func (album Album) PrintArtists() string {
				artists := album.GetUniqueArtists()
				if len(artists) == 1 {
								return artists[0].Name
				}

				names := []string{}
				for _, artist := range artists {
								names = append(names, artist.Name)
				}

				res := strings.Join(names[:len(names) - 1], ", ")
				res += " & " + names[len(names) - 1]
				return res
}

func (album Album) PrintCommaArtists() string {
				if len(album.Credits) == 1 {
								return album.Credits[0].Artist.Name
				}

				artists := album.GetUniqueArtists()
				names := []string{}
				for _, artist := range artists {
								names = append(names, artist.Name)
				}

				return strings.Join(names[:len(names)], ", ")
}

func (album Album) ResolveArtwork() string {
				if album.Artwork != "" {
								return album.Artwork
				}
				return "/img/music-artwork/default.png"
}

func (album Album) GetReleaseYear() int {
				return album.ReleaseDate.Year()
}

func (link AlbumLink) NormaliseName() string {
				re := regexp.MustCompile(`[^a-z0-9]`)
				return strings.ToLower(re.ReplaceAllString(link.Name, ""))
}

func (credit AlbumCredit) ResolveArtist() Artist {
				return *credit.Artist
}
