package ganserv

import (
	"encoding/json"
	"net/http"

	"imuslab.com/zoraxy/mod/utils"
)

func (m *NetworkManager) HandleAddNetwork(w http.ResponseWriter, r *http.Request) {
	networkName, err := utils.PostPara(r, "name")
	if err != nil {
		utils.SendErrorResponse(w, "invalid or empty name given")
		return
	}

	subnetMask, err := utils.PostPara(r, "subnetMask")
	if err != nil {
		utils.SendErrorResponse(w, "invalid or empty subnetMask given")
		return
	}

	// Generate a new UUID for this network
	networkUID := newNetworkID()

	// Create a new network object and add it to the list of networks
	newNetwork := &Network{
		UID:         networkUID,
		Name:        networkName,
		CIDR:        subnetMask,
		Description: "",
		Nodes:       []*Node{},
	}

	err = m.AddNetwork(newNetwork)
	if err != nil {
		utils.SendErrorResponse(w, err.Error())
		return
	}

	// Return the new network ID
	js, _ := json.Marshal(networkUID)
	utils.SendJSONResponse(w, string(js))
}

func (m *NetworkManager) HandleRemoveNetwork(w http.ResponseWriter, r *http.Request) {
	networkID, err := utils.PostPara(r, "id")
	if err != nil {
		utils.SendErrorResponse(w, "invalid or empty network id given")
		return
	}

	err = m.RemoveNetwork(networkID)
	if err != nil {
		utils.SendErrorResponse(w, err.Error())
		return
	}
	utils.SendOK(w)
}

func (m *NetworkManager) HandleListNetwork(w http.ResponseWriter, r *http.Request) {
	netid, _ := utils.GetPara(r, "netid")
	if netid != "" {
		targetNet, err := m.GetNetworkByID(netid)
		if err != nil {
			utils.SendErrorResponse(w, err.Error())
			return
		}

		js, _ := json.Marshal(targetNet)
		utils.SendJSONResponse(w, string(js))

	} else {
		// Return the list of networks as JSON
		js, _ := json.Marshal(m.networks)
		utils.SendJSONResponse(w, string(js))
	}

}
