package main

import (
	"fmt"
	"log"
	"net/http"
	"strconv"
	"html/template"
)

type rub float64

func (r rub) String() string {
	return fmt.Sprintf("%.2f",r)
}

var tmpl *template.Template


func Render(w http.ResponseWriter, req *http.Request) {
	err := tmpl.Execute(w,req)
	if err != nil {
		http.Error(w,err.Error(),http.StatusInternalServerError)
	}
}

type database map[string]rub

type List struct {
	Items database
}

func (db *database) list(w http.ResponseWriter, req *http.Request) {
	data := List{
		Items: *db,
	}

	err := tmpl.ExecuteTemplate(w,"template.html",data)
	if err != nil {
		http.Error(w,err.Error(),http.StatusInternalServerError)
	}
}

func (db *database) price(w http.ResponseWriter,req *http.Request) {
	item := req.URL.Query().Get("item")
	v,ok := (*db)[item]
	if !ok {
		w.WriteHeader(http.StatusNotFound)
		fmt.Fprintf(w,"%s not found in goods list",item)
		return
	}
	fmt.Fprintf(w,"Price of %s is %s",item,v)
}

func (db *database) update(w http.ResponseWriter, req *http.Request) {
	item := req.URL.Query().Get("item")
	price := req.URL.Query().Get("price")
	f,err := strconv.ParseFloat(price,2)
	if err != nil {
		log.Fatal(err)
	}
	(*db)[item] = rub(f)
	fmt.Fprintf(w,"item %s and price %s",item,(*db)[item])
}

// func (db database) ServeHTTP(w http.ResponseWriter, r *http.Request ) {
// 	switch r.URL.Path {
// 	case "/list":
// 		for k,v := range db {
// 			fmt.Fprintf(w,"%s costs %s rub\n",k,v)
// 		}
// 	case "/price":
// 		item := r.URL.Query().Get("item")
// 		v,ok := db[item]
// 		if !ok {
// 			w.WriteHeader(http.StatusNotFound)
// 			fmt.Fprintf(w,"%s not found in goods list",item)
// 			return
// 		}
// 		fmt.Fprintf(w,"Price of %s is %s",item,v)
// 	}
// }

func main()  {
	db := database{
		"sneakers": 10.0,
		"boots": 20,
		}
	// mux.Handle("/list",http.HandlerFunc(db.list))
	// mux.Handle("/price",http.HandlerFunc(db.price))
	tmpl = template.Must(template.ParseFiles("template.html"))
	http.HandleFunc("/list",db.list)
	http.HandleFunc("/price",db.price)
	http.HandleFunc("/update",db.update)
	log.Fatal(http.ListenAndServe(":9090",nil))
}
