package main

import (
	"fmt"
	"html/template"
// "log"
	"os"
	"sort"
	"text/tabwriter"
	"time"
)

type Track struct {
	Title  string
	Artist string
	Album  string
	Year   int
	Length time.Duration
}

var tracks = []*Track{
	{"Go", "Delilah", "From the Roots Up", 2012, length("3m38s")},
	{"Go", "Moby", "Moby", 1992, length("3m37s")},
	{"Go Ahead", "Alicia Keys", "As I Am", 2007, length("4m36s")},
	{"Ready 2 Go", "Martin Solveig", "Smash", 2011, length("4m24s")},
}

var issueList = template.Must(template.New("tracklist").Parse(`
<table>
<tr style='text-align: left'>
  <th>#</th>
  <th>Title</th>
  <th>Artist</th>
  <th>Album</th>
</tr>
{{range .}}
<tr>
  <td>{{.Title}}</td>
  <td>{{.Artist}}</td>
  <td>{{.Album}}</td>
</tr>
{{end}}
</table>
`))


func length(s string) time.Duration {
	d, err := time.ParseDuration(s)
	if err != nil {
		panic(s)
	}
	return d
}

func PrintTracks(tracks []*Track) {
	const format = "%v\t%v\t%v\t%v\t%v\n"
	tw := tabwriter.NewWriter(os.Stdout,0,8,2,' ',0)
	fmt.Fprintf(tw,format,"Title","Artist","Album","Year","Length")
	fmt.Fprintf(tw, format, "-----", "------", "-----", "----", "------")
	for _, t := range tracks {
		fmt.Fprintf(tw,format,t.Title,t.Artist,t.Album,t.Year,t.Length)
	}
	tw.Flush()
}

type byArtists []*Track

func (x byArtists) Len() int {return  len(x)}
func (x byArtists) Less(i,j int) bool {return x[i].Artist < x[j].Artist}
func (x byArtists) Swap(i,j int) { x[i],x[j] = x[j],x[i]}

func main() {
	PrintTracks(tracks)
	fmt.Println()
	sort.Sort(byArtists(tracks))
	PrintTracks(tracks)
	// if err := issueList.Execute(os.Stdout,tracks); err != nil {
	// 	log.Fatal(err)
	// }
}