package main

import (
	"fmt"
	"io/ioutil"
	"log"
	"net/http"

	"github.com/golang/protobuf/proto"
	"github.com/gorilla/mux"
)


func getSchema(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	container := vars["container"]

	//make get request to specified container
	url := fmt.Sprintf("http://%s", container)
	resp, err := http.Get(url)
	if err != nil {
		log.Fatal("Error: ", err)
	}

	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		log.Fatal(err)
	}

	schema := &Schema{}
	err = proto.Unmarshal(body, schema)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(schema)
}

func getStats(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	port := vars["port"]


	//make get request to specified container
	url := fmt.Sprintf("http://localhost:%d", port)
	resp, err := http.Get(url)
	if err != nil {
		log.Fatal("Error: ", err)
	}

	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		log.Fatal(err)
	}

	stats := &ChartComponent{}
	err = proto.Unmarshal(body, stats)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(stats)


}



func handleRequests() {
	myRouter := mux.NewRouter().StrictSlash(true)

	myRouter.HandleFunc("/schema/{container}", getSchema)

	log.Fatal(http.ListenAndServe(":3000", myRouter))
}


func main() {
	fmt.Println("Module API...")
	handleRequests()
}