from app import db, login
from flask_login import UserMixin
from werkzeug.security import check_password_hash


class Glacier(db.Model):
    id = db.Column(db.String(20), primary_key=True)
    country = db.Column(db.String(60))
    name = db.Column(db.String(60))
    annual_data = db.relationship("Annual_Data")

    def __init__(self, id, country, name):
        self.id = id
        self.country = country
        self.name = name


class Annual_Data(db.Model):
    __tablename__ = "annual_data"
    year = db.Column(db.Integer, primary_key=True)
    id = db.Column(db.ForeignKey("glacier.id"), primary_key=True)
    surface = db.Column(db.Float)
    length = db.Column(db.Float)
    elevation = db.Column(db.Float)

    def __init__(self, year, surface, length, elevation):
        self.year = year
        self.surface = surface
        self.length = length
        self.elevation = elevation


class User(UserMixin, db.Model):
    id = db.Column(db.Integer, primary_key=True)
    registration_date = db.Column(
        db.DateTime, nullable=False, server_default=db.func.now()
    )
    username = db.Column(db.String(20), nullable=False, unique=True)
    password_hash = db.Column(db.String(128), unique=True)

    def __init__(self, id, username, password_hash):
        self.id = id
        self.username = username
        self.password_hash = password_hash

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

    @login.user_loader
    def load_user(id):
        return User.query.get(int(id))
