// Copyright (C) 2023 Marius Schellenberger

package core

import (
	"encoding/base32"
	"encoding/base64"
	"encoding/hex"
)

var b32raw = base32.StdEncoding.WithPadding(base32.NoPadding)

type Encoding int

const (
	Hex Encoding = iota
	Base32
	Base64
	Base64URL
)

func (e Encoding) String() string {
	switch e {
	case Base32:
		return "base32"
	case Base64:
		return "base64"
	case Base64URL:
		return "base64url"
	}
	return "hex"
}

func (e Encoding) EncodeToString(src []byte) string {
	switch e {
	case Base32:
		return b32raw.EncodeToString(src)
	case Base64:
		return base64.RawStdEncoding.EncodeToString(src)
	case Base64URL:
		return base64.RawURLEncoding.EncodeToString(src)
	}
	return hex.EncodeToString(src)
}

func (e Encoding) Decode(src string) ([]byte, error) {
	switch e {
	case Base32:
		return b32raw.DecodeString(src)
	case Base64:
		return base64.RawStdEncoding.DecodeString(src)
	case Base64URL:
		return base64.RawURLEncoding.DecodeString(src)
	}
	return hex.DecodeString(src)
}

func EncodingFromString(e string) Encoding {
	switch e {
	case "base32":
		return Base32
	case "base64":
		return Base64
	case "base64url":
		return Base64URL
	}
	return Hex
}
