package main

import (

	"database/sql"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"

    "github.com/labstack/echo/v4"
	"gitlab.computing.dcu.ie/murphg62/2023-ca400-murphg62-byrnm257/src/backend/pkg/database"
	_ "golang.org/x/mod/module"
)

const (
	host = "localhost"
	port = 5432
	user = "postgres"
	password = "Gcvy4266"
	dbname = "Panoptes"
)

var db, err = database.ConnectDB(host, port, user, password, dbname)

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


type Module struct {
	Name string `json:"Name"`
	Container string `json:"Container"`
}


func homePage(c echo.Context) error {
	return c.String(http.StatusOK, "Welcome to the home page!")
}

func getSchema(c echo.Context) error {
	key := c.Param("container")


	requestURL := fmt.Sprintf("http://%s/schema", key)
	resp, err := http.Get(requestURL)
	if err != nil {
		log.Fatalf("Request to container failed: %v", err)
	}

	defer resp.Body.Close()

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

    return c.JSONBlob(http.StatusOK, body)
}

func getStats(c echo.Context) error {
	key := c.Param("container")

	requestURL := fmt.Sprintf("http://%s:8080", key)
	resp, err := http.Get(requestURL)
	if err != nil {
		log.Fatalf("Request to container failed: %v", err)
	}

	defer resp.Body.Close()

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

    return c.JSONBlob(http.StatusOK, body)
}


func GetModules(db *sql.DB) http.HandlerFunc{
	return func(w http.ResponseWriter, r *http.Request) {
		if r.Method == "GET" {
			var Modules []Module
			rows, err := db.Query("Select name, container_name FROM Module")
			if err != nil {
				panic(err)
			}
			defer rows.Close()
			
			for rows.Next() {
				var module Module
				if err := rows.Scan(&module.Name, &module.Container); err != nil {
					panic(err)
				} 
				Modules = append(Modules, module)
			}

			w.Header().Set("Content-Type", "application/json")
			if err := json.NewEncoder(w).Encode(Modules); err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
			}
		}
	}
}

func main() {
    if err != nil {
        panic(err)
    }
    db.Exec(`CREATE TABLE IF NOT EXISTS Module (
                    name VARCHAR(64),
                    container_name VARCHAR(64)
             )`)
    e := echo.New()
    e.GET("/", homePage)
    e.GET("/:container/schema", getSchema)
    e.GET("/:container/stats", getStats)
    e.Logger.Fatal(e.Start(":10000"))
	defer db.Close()
}
