from flask_sqlalchemy import SQLAlchemy
from passlib.hash import sha256_crypt
from flask_login import UserMixin
from datetime import datetime

db = SQLAlchemy()


class User(db.Model, UserMixin):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100))
    email = db.Column(db.String(100), unique=True)
    username = db.Column(db.String(30), unique=True)
    password = db.Column(db.String(100))
    user_information = db.Column(db.String(300))
    registration_date = db.Column(db.DateTime, default=datetime.utcnow)
    last_successful_entry = db.Column(db.DateTime)
    last_address = db.Column(db.String(30))
    is_admin = db.Column(db.Boolean, default=False)


class VirtualMachine(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    hyper = db.Column(db.String(50))
    ip_addres = db.Column(db.String(50))
    id_vm = db.Column(db.String(50))
    name = db.Column(db.String(100))
    os = db.Column(db.String(100))
    memory = db.Column(db.Integer)
    cpu = db.Column(db.Integer)
    power_status = db.Column(db.String(20))
    status = db.Column(db.String(20))
    task = db.Column(db.String(100))
    busy_date = db.Column(db.String(20))
    who_borrowed = db.Column(db.String(20))
    who_borrowed_username = db.Column(db.String(20))
    technical = db.Column(db.Boolean, default=False)
    information = db.Column(db.String(1000))
    appointment = db.Column(db.String(100))


class Stables(db.Model):  # type: ignore
    id = db.Column(db.Integer, primary_key=True)
    monitoring = db.Column(db.String(100))
    printmanager = db.Column(db.String(100))


class Actions(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer)
    action_type = db.Column(db.String(50))
    vm = db.Column(db.Integer)
    action_info = db.Column(db.String(100))
    action_timestamp = db.Column(db.DateTime, default=datetime.now)


def create_user(name, email, username, password):
    hashed_password = sha256_crypt.hash(password)
    new_user = User(name=name, email=email, username=username, password=hashed_password)
    db.session.add(new_user)
    db.session.commit()


def get_user_by_username(username):
    return User.query.filter_by(username=username).first()


def get_vm_by_vms(vmhyper, vmname):
    return VirtualMachine.query.filter_by(hyper=vmhyper, name=vmname).first()
