from __future__ import absolute_import
import hashlib
import os
from .role import AdminUserRole
from dostadmin import db
import six


class AdminUser(db.Model):
    __tablename__ = "adminuser"
    id = db.Column("id", db.Integer, primary_key=True)
    username = db.Column(db.String(50), unique=True, index=True, nullable=False)
    password = db.Column(db.String(256))
    salt = db.Column(db.String(256))
    authenticated = db.Column(db.Boolean)
    phone = db.Column(db.String(10))
    roles = db.relationship("Role", secondary=AdminUserRole)

    def __init__(self, username, password):
        self.username = username
        self.salt = os.urandom(8).hex()
        self.password = hashlib.sha512(
            self.salt.encode() + password.encode()
        ).hexdigest()

        self.authenticated = False

    def authenticate(self, password):
        ip_hash = hashlib.sha512(self.salt.encode() + password.encode()).hexdigest()
        if ip_hash == self.password:
            self.authenticated = True
        return self.authenticated

    def logout(self):
        self.authenticated = False

    def is_authenticated(self):
        return self.authenticated

    def is_active(self):
        return True

    def is_anonymous(self):
        return False

    def get_id(self):
        return six.text_type(self.id)

    def __repr__(self):
        return f"<AdminUser {self.username}>"
