package main

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

func httpHandle() {
	http.HandleFunc("/", IndexHandler)
	http.HandleFunc("/api/client/get", selectAllClientHandler)
	http.HandleFunc("/api/cpu/get", selectCPUPercentHandler)
	http.HandleFunc("/api/memory/get", selectMemoryHandler)
}

func cors(w http.ResponseWriter) {
	w.Header().Set("Access-Control-Allow-Origin", "*")
	w.Header().Add("Access-Control-Allow-Headers", "*")
	//w.Header().Set("content-type","application/json")
}

func IndexHandler(w http.ResponseWriter, r *http.Request) {
	cors(w)
	_, _ = fmt.Fprint(w, "Hello, world!")
}

func selectCPUPercentHandler(w http.ResponseWriter, r *http.Request) {
	cors(w)
	id := r.FormValue("id")
	t := r.FormValue("time")
	if t == "" {
		t = "0"
	}
	time, err := strconv.Atoi(t)
	if err != nil {
		_, _ = fmt.Fprint(w, "Bad params!")
		return
	}
	limit, err := strconv.Atoi(r.FormValue("limit"))
	if err != nil {
		_, _ = fmt.Fprint(w, "Bad params!")
		return
	}
	data, last, err := getCPUPercent(id, int64(time), limit)
	if err != nil {
		_, _ = fmt.Fprint(w, "Could not get data!")
		return
	}
	type result struct {
		Data []CPUPercentDB `json:"data"`
		Last int64          `json:"last"`
	}
	res := result{
		Data: *data,
		Last: last,
	}
	j, err := json.Marshal(res)
	if err != nil {
		_, _ = fmt.Fprint(w, "Could not get data!")
		return
	}
	w.Header().Set("content-type", "application/json")
	_, _ = fmt.Fprintf(w, "%s", j)
}

func selectMemoryHandler(w http.ResponseWriter, r *http.Request) {
	cors(w)
	id := r.FormValue("id")
	t := r.FormValue("time")
	if t == "" {
		t = "0"
	}
	time, err := strconv.Atoi(t)
	if err != nil {
		_, _ = fmt.Fprint(w, "Bad params!")
		return
	}
	limit, err := strconv.Atoi(r.FormValue("limit"))
	if err != nil {
		_, _ = fmt.Fprint(w, "Bad params!")
		return
	}
	data, last, err := getMemory(id, int64(time), limit)
	if err != nil {
		_, _ = fmt.Fprint(w, "Could not get data!")
		return
	}
	type result struct {
		Data []MemoryDB `json:"data"`
		Last int64      `json:"last"`
	}
	res := result{
		Data: *data,
		Last: last,
	}
	j, err := json.Marshal(res)
	if err != nil {
		_, _ = fmt.Fprint(w, "Could not get data!")
		return
	}
	w.Header().Set("content-type", "application/json")
	_, _ = fmt.Fprintf(w, "%s", j)
}

func selectAllClientHandler(w http.ResponseWriter, r *http.Request) {
	cors(w)
	data, err := getClient()
	if err != nil {
		fmt.Println(err)
		_, _ = fmt.Fprint(w, "Could not get data!")
		return
	}
	j, err := json.Marshal(data)
	if err != nil {
		_, _ = fmt.Fprint(w, "Could not get data!")
		return
	}
	w.Header().Set("content-type", "application/json")
	_, _ = fmt.Fprintf(w, "%s", j)
}
