package fr.isima.stackoverflow

import groovy.transform.EqualsAndHashCode
import groovy.transform.ToString

@EqualsAndHashCode(includes='username')
@ToString(includes='username', includeNames=true, includePackage=false)
class User implements Serializable 
{
	// Attributes
	private static final long serialVersionUID = 1

	transient springSecurityService

	// Auto-Generated by Spring Security Core Plugin
	String username
	String password
	boolean enabled = true
	boolean accountExpired
	boolean accountLocked
	boolean passwordExpired

	// Custom fields
	Date registerDate = new Date()
	Integer reputation = 0
	String description = ""

	// Constraints
	static transients = ['springSecurityService']

	static constraints = {
		password password: true, minSize: 6
		username unique: true, minSize: 3, maxSize: 50
		description maxSize: 65535
		reputation min: 0
	}

	static mapping = {
		password column: '`password`'
	}
	
	// Relations
	static hasMany = [questions: Question, answers: Answer, votes: Vote]
	
	// Member functions
	Set<Role> getAuthorities() 
	{
		UserRole.findAllByUser(this)*.role
	}

	def beforeInsert() 
	{
		encodePassword()
	}

	def beforeUpdate() 
	{
		if (isDirty('password')) 
		{
			encodePassword()
		}
	}

	protected void encodePassword() 
	{
		password = springSecurityService?.passwordEncoder ? springSecurityService.encodePassword(password) : password
	}
}
