package virtbuf

import (
	"encoding/json"
	"fmt"
	"strconv"
)

// MarshalJSON custom marshals the WhatInfo struct to JSON
func (s WhatInfo) MarshalJSON() ([]byte, error) {
	capacityStr := fmt.Sprintf("%d GB", s.Capacity)
	return json.Marshal(map[string]string{
		"capacity": capacityStr,
	})
}

func (s WhatInfo) FormatJSON() string {
	return fmt.Sprintf("\"capacity\": \"%d GB\"", s.Capacity)
}

// UnmarshalJSON custom unmarshals JSON into the WhatInfo struct
func (s *WhatInfo) UnmarshalJSON(data []byte) error {
	var raw map[string]string
	if err := json.Unmarshal(data, &raw); err != nil {
		return err
	}

	if capacityStr, ok := raw["capacity"]; ok {
		capacityStr = capacityStr[:len(capacityStr)-3] // Remove the " GB" suffix
		capacity, err := strconv.ParseInt(capacityStr, 10, 64)
		if err != nil {
			return err
		}
		s.Capacity = capacity
	}

	return nil
}

/*
func main() {
	info := WhatInfo{Capacity: 64}

	// Marshaling to JSON
	jsonData, _ := json.Marshal(info)
	fmt.Println(string(jsonData)) // Output: {"capacity":"64 GB"}

	// Unmarshaling back to Go struct
	var newInfo WhatInfo
	_ = json.Unmarshal(jsonData, &newInfo)
	fmt.Println(newInfo.Capacity) // Output: 64
}
*/
