// Monitor endpoint
func Monitor(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	name := vars["name"]
	endpoint := vars["endpoint"]

	endpointNo, err := strconv.Atoi(endpoint)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	cfg, err := config.GetConfig()
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	content := ""
	var dashboard *config.Dashboard
	for _, d := range cfg.Dashboards {
		if d.Name == name {
			dashboard = &d
			break
		}
	}
	if dashboard == nil {
		http.Error(w, "Wrong dashboard name", http.StatusInternalServerError)
		return
	}

	if dashboard.Type == "circleci" {
		if endpointNo < 1 || endpointNo > len(dashboard.Endpoints) {
			http.Error(w, "Wrong endpoint number", http.StatusInternalServerError)
			return
		}
		endpoint := dashboard.Endpoints[endpointNo-1]

		d := api.NewDashboardCircleCI(endpoint.Token, endpoint.User, endpoint.Project, endpoint.Branch)
		content, err = d.Render()
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
	}

	fmt.Fprint(w, content)
}
// Dashboard endpoint
func Dashboard(w http.ResponseWriter, r *http.Request) {
	cfg, err := config.GetConfig()
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	content := ""
	for _, dashboard := range cfg.Dashboards {
		if dashboard.Type == "circleci" {
			for _, endpoint := range dashboard.Endpoints {
				d := api.NewDashboardCircleCI(endpoint.Token, endpoint.User, endpoint.Project, endpoint.Branch)
				cnt, err := d.Render()
				if err != nil {
					http.Error(w, err.Error(), http.StatusInternalServerError)
					return
				}
				content += cnt
			}
		}
	}

	t, err := template.New("Dashboard_Main").ParseFiles("templates/main.html")
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	var output bytes.Buffer
	err = t.ExecuteTemplate(&output, "main.html", Content{Content: template.HTML(content)})
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	fmt.Fprint(w, output.String())
}