package main

import (
	"encoding/json"
	"io"
	"io/ioutil"
	"net/http"
)

type ZkSwitch struct {
	Restarts bool `json:"restarts"`
	Cleanup  bool `json:"cleanup"`
	Backups  bool `json:"backups"`
}

type ZkState struct {
	Switches    ZkSwitch `json:"switches"`
	State       uint8    `json:"state"`
	Description string   `json:"description"`
	IsLeader    bool     `json:"isLeader"`
}

func checkState(nodeState ZkState) bool {
	if nodeState.State == 3 {
		return true
	} else {
		return false
	}
}

func checkZkState(w http.ResponseWriter, r *http.Request) {

	var sendOK bool = true

	resp, err := http.Get("http://localhost:8080/exhibitor/v1/cluster/state")
	defer resp.Body.Close()

	if err != nil {
		sendOK = false
	} else {

		body, err := ioutil.ReadAll(resp.Body)

		if err != nil {
			sendOK = false
		} else {

			var zkstateArray ZkState
			json.Unmarshal([]byte(string(body)), &zkstateArray)

			if !checkState(zkstateArray) {
				sendOK = false
			}
		}
	}

	if sendOK {
		w.WriteHeader(http.StatusOK)
		io.WriteString(w, "Zk is healthy")
	} else {
		w.WriteHeader(http.StatusInternalServerError)
		io.WriteString(w, "Zk is NOT healthy - not serving")
	}
}

func consulCheck() {
	http.HandleFunc("/zk/state", checkZkState)
	http.ListenAndServe(":8000", nil)
}
