package cryptosquare

import (
	"math"
	"regexp"
	"strings"
)

// TestVersion is an exercism thing
const TestVersion = 1

// Encode implements the classic method for composing
// secret messages called a square code
func Encode(txt string) string {
	r := regexp.MustCompile("[^a-zA-Z0-9]+")
	nrm := strings.ToLower(r.ReplaceAllString(txt, ""))
	// The string should be normalized now (alphanumeric, lower case)
	sqrt := int(math.Ceil(math.Sqrt(float64(len(nrm)))))
	var square, ret []string
	var tmp string

	// Build the initial square
	for i := 0; i < len(nrm); i++ {
		if i%sqrt == 0 && len(tmp) != 0 {
			square = append(square, tmp)
			tmp = ""
		}
		tmp += string(nrm[i])
	}
	square = append(square, tmp)
	tmp = ""

	// Now rebuild the string by columns
	for i := 0; i < len(square[0]); i++ {
		for j := 0; j < len(square); j++ {
			if i < len(square[j]) {
				tmp += string(square[j][i])
			}
		}
		ret = append(ret, tmp)
		tmp = ""
	}

	return strings.Join(ret, " ")
}
