package form

import (
	"errors"
	"net/http"
	"regexp"
)

type RegisterForm struct {
	Username  string
	Password  string
	Email     string
	ShowEmail bool
	Answer    string
	Confirm   string
	Key       string
	Error     string
}

func (f *RegisterForm) Validate() error {
	if f.Password != f.Confirm {
		return errors.New("password doesn't match confirmation")
	}
	if len(f.Username) < 3 {
		return errors.New("username needs to be at least 3 characters")
	}
	if len(f.Username) > 20 {
		return errors.New("username should be 20 characters or less")
	}
	match, _ := regexp.MatchString("^[a-z0-9-_]+$", f.Username)
	if !match {
		return errors.New("only lowercase letters and digits are accepted for username")
	}
	if len(f.Password) < 6 {
		return errors.New("password needs to be at least 6 characters")
	}
	return nil
}

func NewRegisterForm(r *http.Request) *RegisterForm {
	return &RegisterForm{
		Username:  r.FormValue("name"),
		Password:  r.FormValue("password"),
		Confirm:   r.FormValue("password-confirm"),
		Email:     r.FormValue("email"),
		ShowEmail: r.FormValue("show-email") == "1",
		Answer:    r.FormValue("answer"),
		Key:       r.FormValue("key"),
	}
}
