package rest

import (
	"encoding/hex"
	"encoding/json"
	"fmt"
	"github.com/gorilla/mux"
	"nbarest/lib/persistence"
	"net/http"
	"strings"
)

func NewPlayerServiceHandler(handler persistence.DatabaseHandler) *playerServiceHandler{
	return &playerServiceHandler{
		dbhandler: handler,
	}
}

type playerServiceHandler struct{
	dbhandler persistence.DatabaseHandler
}

func (ph *playerServiceHandler) FindPlayerHandler(w http.ResponseWriter,r *http.Request){
	fmt.Println("FindPlayerHandler")
	vars:=mux.Vars(r)
	criteria,ok:=vars["SearchCriteria"]
	if !ok{
		w.WriteHeader(400)
		fmt.Fprintln(w,"error")
		return
	}

	searchkey,ok:=vars["search"]
	if !ok{
		w.WriteHeader(400)
		fmt.Fprintln(w,"error")
		return
	}

	var player persistence.Player
	var err error

	switch strings.ToLower(criteria) {
	case "name":
		player,err=ph.dbhandler.FindPlayerByName(searchkey)
	case "id":
		id,err:=hex.DecodeString(searchkey)
		if err==nil{
			player,err=ph.dbhandler.FindPlayer(id)
		}
	}
	if err!=nil{
		fmt.Fprintln(w,`{"error"} "%s"`,err)
		return
	}
	fmt.Println("find"+searchkey)
	w.Header().Set("Content-Type","application/json;charset=utf8")
	json.NewEncoder(w).Encode(&player)
}

func (ph *playerServiceHandler) NewPlayerHandler(w http.ResponseWriter, r *http.Request){
	fmt.Println("NewPlayerHandler")
	player:= persistence.Player{}
	err:=json.NewDecoder(r.Body).Decode(&player)
	if err!=nil{
		w.WriteHeader(500)
		fmt.Fprintln(w,`{"error"}`)
		return
	}

	id,err:=ph.dbhandler.AddPlayer(player)
	if nil!=err{
		w.WriteHeader(500)
		fmt.Fprintln(w,`{"error"}`)
		return
	}
	fmt.Fprint(w,`{"id":%d}`,id)
}

func (ph *playerServiceHandler) FindAllPlayerHandler(w http.ResponseWriter,r *http.Request){
	fmt.Println("FindAllPlayerHandler")
	players,err:= ph.dbhandler.FindAllAvailablePlayers()
	if err!=nil{
		w.WriteHeader(500)
		fmt.Fprintln(w,`{"error"}`)
		return
	}

	w.Header().Set("Content-Type", "application/json;charset=utf8")
	err=json.NewEncoder(w).Encode(&players)
	if err!=nil{
		w.WriteHeader(500)
		fmt.Fprintln(w,`{"error"}`)
	}

}