package prettify

import (
	"encoding/json"
	"fmt"
	"reflect"

	"github.com/TylerBrock/colorjson"
)

// Print will beautify the output of v
func Print(v any) {
	typeOfVar := reflect.TypeOf(v)
	switch typeOfVar.Kind() {
	case reflect.Slice:
		pprintArray(v)
	case reflect.Struct:
		pprint(v)
	}
}

// pprint will beautify the output of body
func pprint(body any) error {
	b, err := json.Marshal(body)
	if err != nil {
		return err
	}
	var obj map[string]any
	json.Unmarshal(b, &obj)

	// Make a custom formatter with indent set
	f := colorjson.NewFormatter()
	f.Indent = 2

	// Marshal the Colorized JSON
	s, err := f.Marshal(obj)
	if err != nil {
		return err
	}

	// Print out string to stdout
	fmt.Printf("%s\n", s)
	return nil
}

// pprintArray will beautify the output of bodyArray
func pprintArray(bodyArray any) error {
	b, err := json.Marshal(bodyArray)
	if err != nil {
		return err
	}
	var obj []map[string]any
	json.Unmarshal(b, &obj)

	// Make a custom formatter with indent set
	f := colorjson.NewFormatter()
	f.Indent = 2

	for i := range obj {
		// Marshal the Colorized JSON
		s, err := f.Marshal(obj[i])
		if err != nil {
			return err
		}

		// Print out string to stdout
		fmt.Printf("%s", s)

		// include a comma between elements
		if i < len(obj)-1 {
			fmt.Printf(",")
		}
		// include newline at the end of all elements
		fmt.Printf("\n")
	}
	return nil
}