package module

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

// helpers for repositorys

// JSONEncode encodes an interface to json encoded byte array, formatted if debug is enabled
func JSONEncode(v interface{}) ([]byte, error) {
	var (
		err     error
		rawJSON []byte
	)

	if Conf.Debug {
		rawJSON, err = json.MarshalIndent(v, "", " ") // debug output
		if err != nil {
			log.Println("MARSHAL FAILED")
			log.Println(err)
			return []byte(""), err
		}
	} else {
		rawJSON, err = json.Marshal(v) // prod
		if err != nil {
			log.Println("MARSHAL FAILED")
			log.Println(err)
			return []byte(""), err
		}
	}

	return rawJSON, nil
}

// JSONDecode decodes given JSON into passed interface object
func JSONDecode(rawJSON []byte, v interface{}) error {
	return json.Unmarshal(rawJSON, v)
}

// JSONReq decodes POST data in request body in passed interface
func JSONReq(r *http.Request, v interface{}) {
	json.NewDecoder(r.Body).Decode(v)
}

// JSONResp encodes passed interface and responses the request with interface JSON encoded
func JSONResp(w http.ResponseWriter, v interface{}) {
	enc := json.NewEncoder(w)
	if Conf.Debug {
		enc.SetIndent("", " ")
	}

	enc.Encode(v)
}