package main

import (
	"fmt"
	"log"
	"net/http"
	"io/ioutil"
	"github.com/gorilla/mux"
)

type Schema struct {
	Name string `json:"Name"`
	Type int `json:"Type"`
}

type Container struct {
	Id string `json:"Id`
	Name string `json:"Name"`
	port string `json:"Port"` 
}

var Containers []Container

func homePage(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "Welcome to the home page!")
}

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

	for _, container := range Containers {
		if container.Id == key {
			requestURL := fmt.Sprintf("http://%s:%s/schema", container.Name, container.port)
			resp, err := http.Get(requestURL)
			if err != nil {
				log.Fatal("Request to container failed: %v", err)
			}

			defer resp.Body.Close()

			body, err := ioutil.ReadAll(resp.Body)
			if err != nil {
				log.Fatal("Failed to print Body: %v", err)
			}

			fmt.Fprintf(w,string(body))
		}
	}

}

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

	for _, container := range Containers {
		if container.Id == key {
			requestURL := fmt.Sprintf("http://%s:%s/stats", container.Name, container.port)
			resp, err := http.Get(requestURL)
			if err != nil {
				log.Fatal("Request to container failed: %v", err)
			}

			defer resp.Body.Close()

			body, err := ioutil.ReadAll(resp.Body)
			if err != nil {
				log.Fatal("Failed to print Body: %v", err)
			}

			fmt.Fprintf(w,string(body))
		}
	}

}

func handleRequests() {
	myRouter := mux.NewRouter().StrictSlash(true)
	myRouter.HandleFunc("/", homePage)
	myRouter.HandleFunc("/{container}/schema", getSchema)
	myRouter.HandleFunc("/{container}/stats", getStats)

	log.Fatal(http.ListenAndServe(":10000", myRouter))

}

func main() {

	Containers = []Container{
		Container{Id: "1", Name: "localhost", port: "3000"},
	}

	handleRequests()
}