# -*- coding: utf-8 -*-

from flask.ext.login import UserMixin

from pwnurl.common.extensions import db
from pwnurl.models.base import BaseModel
from pwnurl.models import Role

from pwnurl.models.mixin.created import CreatedMixin

from werkzeug.security import generate_password_hash, check_password_hash


class User(db.Model, BaseModel, UserMixin, CreatedMixin):

    __tablename__ = 'users'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String)
    email = db.Column(db.String(64), unique=True, index=True)
    username = db.Column(db.String(64), unique=True, index=True)
    password_hash = db.Column(db.String(128))
    role_id = db.Column(db.Integer, db.ForeignKey('roles.id'))

    def __init__(self, **kwargs):
        super(User, self).__init__(**kwargs)
        if self.role is None:
            self.role = Role.query.filter_by(default=True).first()

    @property
    def password(self):
        raise AttributeError('password is not a readable attribute')

    @password.setter
    def password(self, password):
        self.password_hash = generate_password_hash(password)

    def verify_password(self, password):
        return check_password_hash(self.password_hash, password)
