from flask import render_template, jsonify,flash,redirect,url_for
from flask_sqlalchemy import SQLAlchemy
from flask_login import UserMixin
from datetime import datetime
from sqlalchemy import Column, Integer, String, MetaData, Table

db = SQLAlchemy()


###USER MODULE###
class User(UserMixin,db.Model):
    id = db.Column(db.Integer,primary_key=True,autoincrement=True)
    username = db.Column(db.String(64),index=True,unique=True)
    email=db.Column(db.String(64))
    role=db.Column(db.String(64))
    password = db.Column(db.String(128))
    is_active = db.Column(db.Boolean, default=True)
    created_by = db.Column(db.String(64))
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)

    def get_id(self):
        return(self.id)
    
class DBData(UserMixin,db.Model):
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    connection_name = db.Column(db.String(64))
    hostname = db.Column(db.String(255))
    port = db.Column(db.Integer)
    username = db.Column(db.String(64))
    schemaname=db.Column(db.String(64))
    password = db.Column(db.String(128))
    tablename=db.Column(db.String(64))
    created_by = db.Column(db.String(64))
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
    status=db.Column(db.Integer)

    def get_id(self):
        return(self.id)
    
class data(db.Model):
    
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    file_path = db.Column(db.String(256), nullable=False)
    inserted_rows = db.Column(db.Integer)
    updated_rows = db.Column(db.Integer)
    uploaded_by = db.Column(db.Integer)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)

    def get_id(self):
        return(self.id)
    
class data_error(db.Model):
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    file_id = db.Column(db.Integer)
    clm_name = db.Column(db.String(256))
    index = db.Column(db.Integer)
    error = db.Column(db.String(256))
    status = db.Column(db.Integer)
    
    def get_id(self):
        return(self.id)
#def create_dynamic_model(table_name, column_names):
#     global DynamicModel

#     # Check if the model class already exists
#     if DynamicModel is not None:
#         return DynamicModel

#     class DynamicModel(db.Model):
#         __tablename__ = table_name
#         id = Column(Integer, primary_key=True, autoincrement=True)

#     for column_name in column_names:
#         column = Column(String(255))  # Change the data type to match your requirements
#         setattr(DynamicModel, str(column_name), column)  # Convert the column name to a string

#     # Store the model class in the global variable
#     DynamicModel = DynamicModel

#     return DynamicModel