package view

import (
	"encoding/json"
	"io/ioutil"
	"local/dndex/storage"
	"local/dndex/storage/entity"
	"net/http"

	"github.com/buger/jsonparser"
)

func port(g storage.Graph, w http.ResponseWriter, r *http.Request) error {
	switch r.Method {
	case http.MethodGet:
		return portGet(g, w, r)
	case http.MethodPost:
		return portPost(g, w, r)
	default:
		http.NotFound(w, r)
		return nil
	}
}

func portGet(g storage.Graph, w http.ResponseWriter, r *http.Request) error {
	namespace, err := getNamespace(r)
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return nil
	}

	ones, err := g.List(r.Context(), namespace)
	if err != nil {
		return err
	}

	return json.NewEncoder(w).Encode(map[string]interface{}{namespace: ones})
}

func portPost(g storage.Graph, w http.ResponseWriter, r *http.Request) error {
	namespace, err := getNamespace(r)
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return nil
	}

	b, err := ioutil.ReadAll(r.Body)
	if err != nil {
		return err
	}

	inserted := 0

	var errIn error
	_, err = jsonparser.ArrayEach(b, func(b []byte, _ jsonparser.ValueType, _ int, err error) {
		if err != nil {
			errIn = err
			return
		}

		o := entity.One{}
		if err := json.Unmarshal(b, &o); err != nil {
			errIn = err
			return
		}

		if err := g.Insert(r.Context(), namespace, o); err != nil {
			errIn = err
			return
		}

		inserted += 1
	}, namespace)
	if err != nil {
		return err
	}
	if errIn != nil {
		return errIn
	}

	return json.NewEncoder(w).Encode(map[string]int{namespace: inserted})
}
