# Based on https://mariadb.com/resources/blog/how-to-connect-python-programs-to-mariadb/
import mariadb
import sys
import datetime
#stores current time
currentTime = datetime.datetime.now()

#Connects to the databse
def connect(dbName):
    # Connect to MariaDB Platform
    try:
        conn = mariadb.connect(
            user="root",
            password="KyKvMdRt586591!*",
            host="db.keydev.me",
            port=3306,
            database=dbName
        )
        print(type(conn))
    except mariadb.Error as e:
        print(f"Error connecting to MariaDB Platform: {e}")
        return e
        sys.exit(1)
     
    conn.autocommit = False    
    return conn

#Get all the column naes of the given table
def getColumnNames(cursor, table):
    command = "SHOW COLUMNS FROM " + table
    cursor.execute(command)
    colName = []
    index = 0
    for row in cursor:
        colName.append(row[0])
    return colName

#Gets all the Foreign Keys of the given table
def getForeignKeys(cursor, table):
    command = "SHOW INDEX FROM " + table
    cursor.execute(command)
    colName = []
    index = 0
    for row in cursor:
        if not row[2] == "PRIMARY":
            colName.append(row[4])
    return colName

#Gets all the Primary Keys of the given table
def getPrimaryKey(cursor, table):
    command = "SHOW INDEX FROM " + table
    cursor.execute(command)
    index = 0
    for row in cursor:
        if row[2] == "PRIMARY":
            pk = row[4]
    return pk

#Returns all the raws of the desired columns from the selected table
def select(cursor,table,columns):
    buffer=[] 
    command = "SELECT "+columns+" FROM "+table
   
    try:
        cursor.execute(command)
    except mariadb.Error as e:
        print(f"Error: {e}")
  
    for row in cursor:
        buffer.append(row)
    return buffer

#Returns the rows coreponding to the WHERE condition and desired colums from the selected table
#If no data is to be fount the function returns 0
def selectWhere(cursor,table,columns,where,equals):
    buffer=[] 
    command = "SELECT "+columns+" FROM "+table+" WHERE "+where+"='"+equals+"'" 
    print(command)
    try:
        cursor.execute(command)
    except mariadb.Error as e:
        print(f"Error: {e}")
  
    for row in cursor:
        buffer.append(row)
    if len(buffer) == 0:
        return 0
    else:
        return buffer

def insert(cursor,table,column,data):
    command = "INSERT INTO "+table+" ("+column+") VALUES ("+data+")"
    try:
        cursor.execute(command)
    except mariadb.Error as e:
        print(f"Error: {e}")

def update(cursor,table,data,where,equals):
    command = "INSERT INTO "+table+" ("+column+") VALUES ("+data+")"
    
def delete(cursor,table,column):
    command = "INSERT INTO "+table+" ("+column+") VALUES ("+data+")"
