from datetime import datetime, timedelta

import jwt
from flask import current_app
from werkzeug.security import generate_password_hash, check_password_hash
from sqlalchemy.orm import relationship

from restdemo import db
from restdemo.model.base import Base

class User(Base):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(64), unique=True)
    password_hash = db.Column(db.String(128))
    email = db.Column(db.String(64))

    tweet = relationship('Tweet')   #设置关联对象

    def __repr__(self):
        return "id={}, username={}, password_hash={}, email={}".format(
            self.id, self.username, self.password_hash, self.email
        )

    def set_password(self, password):
        #转化密码为哈希值
        self.password_hash = generate_password_hash(password)

    def check_password(self, password):
        #检查哈希值密码是否正确
        return check_password_hash(self.password_hash, password)

    @staticmethod
    def get_by_username(username):
        return db.session.query(User).filter(
            User.username == username
        ).first()

    @staticmethod
    def get_by_id(user_id):
        return db.session.query(User).filter(
            User.id == user_id
        ).first()

    @staticmethod
    def get_user_list():
        return db.session.query(User).all()

    @staticmethod
    def authenticate(username, password):
        user = User.get_by_username(username)
        if user:
            # check password
            if user.check_password(password):
                return user
    @staticmethod
    def identity(payload):
        user_id = payload['identity']
        user = User.get_by_id(user_id)
        return user