package handlers

import (
	"encoding/json"
	"fmt"
	"net/http"
	"time"
)

var startTime = time.Now()

func GreetingHandler(writer http.ResponseWriter, request *http.Request) {
	decoder := json.NewDecoder(request.Body)
	decoder.DisallowUnknownFields()
	var p = PersonRequest{}
	errDecode := decoder.Decode(&p)
	if errDecode != nil {
		println("Error: ", errDecode)
		writer.WriteHeader(400)
		_, _ = writer.Write([]byte("Bad request data"))
		return
	}

	r := PersonResponse{
		Greeting: fmt.Sprintf("Hey %s. Your age is %d", p.Name, p.Age),
		Errors:   "",
	}

	writer.Header().Add("Content-Type", "application/json")
	encoder := produceEncoder(writer)
	errEncode := encoder.Encode(&r)
	if errEncode != nil {
		writer.WriteHeader(500)
		println("Error: ", errEncode)
		return
	}
	writer.WriteHeader(200)
}

func produceEncoder(writer http.ResponseWriter) *json.Encoder {
	encoder := json.NewEncoder(writer)
	return encoder
}

func StatusHandler(writer http.ResponseWriter, _ *http.Request) {
	upTime := time.Now().Unix() - startTime.Unix()
	status := StatusResponse{
		Status:        "Ok",
		StartDateTime: startTime.Format("2006-01-02 15:04:05.000-0700"),
		UpTime:        fmt.Sprintf("%d", upTime),
	}

	writer.Header().Add("Content-Type", "application/json")
	encoder := produceEncoder(writer)
	errEncode := encoder.Encode(&status)
	if errEncode != nil {
		writer.WriteHeader(500)
		println("Error: ", errEncode)
		return
	}
	writer.WriteHeader(200)
}
