// go.stargrave.org/tai64n -- Pure Go TAI64/TAI64N implementation
// Copyright (C) 2020-2026 Sergey Matveev <stargrave@stargrave.org>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, version 3 of the License.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

package tai64n

import (
	"encoding/hex"
	"errors"
	"strings"
	"time"
)

func (tai *TAI64) Encode() string {
	raw := make([]byte, 1+TAI64Size*2)
	raw[0] = '@'
	hex.Encode(raw[1:], tai[:])
	return string(raw)
}

func (tai *TAI64N) Encode() string {
	raw := make([]byte, 1+TAI64NSize*2)
	raw[0] = '@'
	hex.Encode(raw[1:], tai[:])
	return string(raw)
}

// Convert "@HEX(TAI64(N?))" format to Time.
func Decode(s string) (t time.Time, err error) {
	var raw []byte
	raw, err = hex.DecodeString(strings.TrimPrefix(s, "@"))
	if err != nil {
		return
	}
	switch len(raw) {
	case TAI64Size:
		tai := TAI64(raw)
		return tai.Time(), nil
	case TAI64NSize:
		tai := TAI64N(raw)
		return tai.Time(), nil
	}
	err = errors.New("unsupported length")
	return
}
