package codes

import (
	"crypto/rand"
	"encoding/base64"
	"math/big"
	"strings"
)

const codeLen = 32

func NewCode(email string) string {
	charset := "abcdefghijklmnopqrztuvwxyz"
	charset += strings.ToUpper(charset)
	charset += "0123456789"
	charset += "`~!@#$%^&*()-=_+[]{}|;:,./<>?"

	code := []byte{}

	max := big.NewInt(int64(len(charset)))
	for len(code) < codeLen {
		ix, err := rand.Int(rand.Reader, max)
		if err != nil {
			// TODO this is bad but I'm just kind of hoping it doesn't happen...often
			panic(err)
		}
		code = append(code, charset[ix.Int64()])
	}

	code = append(code, ' ')

	eb := []byte(email)
	for x := 0; x < len(eb); x++ {
		code = append(code, eb[x])
	}

	return base64.StdEncoding.EncodeToString(code)
}

func Decode(code string) ([]string, error) {
	decoded, err := base64.StdEncoding.DecodeString(code)
	if err != nil {
		return nil, err
	}

	return strings.Split(string(decoded), " "), nil
}