package main

import (
	"Study/pkg/GithubApi"
	"html/template"
	"log"
	"net/http"
	"strconv"
	"time"
)

var Issues = template.Must(template.New("issuelist").
	Funcs(template.FuncMap{"dayAgo": daysFormat}).
	Parse(`
<h1>{{.TotalCount}} issues</h1>
<table>
<tr style='text-align: left'>
  <th>#</th>
  <th>State</th>
  <th>Date</th>
  <th>User</th>
  <th>Title</th>
</tr>
{{range .Items}}
<tr>
  <td><a href='{{.HTMLURL}}'>{{.Number}}</a></td>
  <td>{{.State}}</td>
  <td>{{.CreatedAt | dayAgo}}</td>
  <td><a href='{{.User.HTMLURL}}'>{{.User.Login}}</a></td>
  <td><a href='{{.HTMLURL}}'>{{.Title}}</a></td>
</tr>
{{end}}
</table>
`))

const layout = "2006-01-02 15:04:05"

func daysAgo(t time.Time) float64 {
	return time.Since(t).Hours() / 24.0
}
func daysFormat(t time.Time) string {
	return t.Format(layout)
}
func main() {
	http.HandleFunc("/", serch)
	log.Fatal(http.ListenAndServe("0.0.0.0:8080", nil))
}

func serch(w http.ResponseWriter, r *http.Request) {
	vars := r.URL.Query()

	s := vars.Get("s")
	if s == "" {
		s = "repo:golang/go"
	}
	date := vars.Get("date")
	if date == "" {
		date = "30"
	}
	dateI, _ := strconv.Atoi(date)
	res, err := GithubApi.SearchIssues([]string{s}, dateI, "")
	//res, err := github.SearchIssues([]string{"repo:golang/go"})
	if err != nil {
		log.Fatal(err)
	}
	if err := Issues.Execute(w, res); err != nil {
		log.Fatal(err)
	}
}
