package orm

import (
	"crypto/sha1"
	"encoding/base64"
	"fmt"
	"strings"
	"time"

	"github.com/jinzhu/gorm"
	"github.com/sethvargo/go-password/password"
)

type Checkbox bool

type Credential struct {
	gorm.Model

	Name          string `csv:"firstname"`
	Surname       string `csv:"lastname"`
	Password      string
	PlainPassword string
	Email         string `csv:"email"`
	AltEmail      string
	DateFrom      time.Time
	DateTo        time.Time

	TelephoneNumber         string
	InternalTelephoneNumber string

	Regenerate bool `schema:"Regenerate" sql:"default: false"`
	Exclude    bool
	NotInvited bool

	LdapDNFmt string
}

func (c *Credential) sanitize(s string) string {
	lower := strings.ToLower(s)
	r := strings.NewReplacer("'", "", "-", "", " ", "", "ò", "o", "ì", "i")
	return r.Replace(lower)
}

func (c *Credential) Username() string {
	return strings.Join([]string{c.sanitize(c.Name), c.sanitize(c.Surname)}, ".")
}

func (c *Credential) GeneratePassword() (string, error) {
	password, err := password.Generate(8, 2, 0, false, true)
	if err != nil {
		return "", err
	}
	return password, nil

}

func (c *Credential) CompleteName() string {
	return fmt.Sprintf("%s %s", c.Name, c.Surname)
}

func (c *Credential) MailAddress(domain string) string {
	return fmt.Sprintf("%s@%s", c.Username(), domain)
}

func (c *Credential) DN() string {
	return fmt.Sprintf(c.LdapDNFmt, c.Name, c.Surname)
}

func (c *Credential) GetName() string {
	return c.Name
}

func (c *Credential) GetSurname() string {
	return c.Surname
}

func (c *Credential) GetExclude() bool {
	return c.Exclude
}

func (c *Credential) IsInvited() bool {
	return !c.NotInvited
}

func (c *Credential) GetRegenerate() bool {
	return c.Regenerate
}

func (c *Credential) SetRegenerate(value bool) {
	c.Regenerate = value
}

func (c *Credential) GetPlainPassword() string {
	return c.PlainPassword
}

func (c *Credential) SetPlainPassword(password string) {
	c.PlainPassword = password
}

func (c *Credential) GetEmail() string {
	return c.Email
}

func (c *Credential) GetAltEmail() string {
	return c.AltEmail
}

func SaltPassword(password string) string {
	bs := sha1.Sum([]byte(password + "salt"))
	str := base64.StdEncoding.EncodeToString(append(bs[:], []byte("salt")...))
	return fmt.Sprintf("%s", str)
}
