package ii

import (
	"encoding/json"
	"encoding/xml"
	"fmt"
	"strings"
)

type Name string

func (n *Name) Database() string {
	dbName, _, found := strings.Cut(n.String(), ".")
	if !found {
		return ""
	}
	return dbName
}

func (n *Name) Collection() string {
	_, colName, found := strings.Cut(n.String(), ".")
	if !found {
		return ""
	}
	return colName
}

func (n *Name) String() string {
	return string(*n)
}

func (n *Name) UnmarshalXMLAttr(attr xml.Attr) error {
	name := strings.Split(attr.Value, ".")
	if len(name) != 2 {
		return fmt.Errorf("itemname error: %s", attr.Value)
	}
	if strings.TrimSpace(name[0]) == "" || strings.TrimSpace(name[1]) == "" {
		return fmt.Errorf("itemname error: %s", attr.Value)
	}
	*n = Name(attr.Value)
	return nil
}

func (n *Name) MarshalJSON() ([]byte, error) {
	value := fmt.Sprintf(`"%s"`, n)
	return []byte(value), nil
}

func (n *Name) UnmarshalJSON(v []byte) error {
	var temp string
	if err := json.Unmarshal(v, &temp); err != nil {
		return err
	}
	*n = Name(temp)
	return nil
}
