import sqlite3
import pandas as pd
import os
import types
from datetime import datetime

# from utils.sql_command import *

from .sql_command import *
from .ANSI_color import *

'''
Database:

venv_info(id, project_path, venv_name, created_date, requirement_file, connect_status)

'''

def check_database(con):
    cur = con.cursor()
    cur.execute(create_venv_info_sql)

def connect_check_database(database_path: str):
    con = sqlite3.connect(database_path)
    check_database(con)
    return con

def insert_data_into_venv_info(con: sqlite3.Connection, *args, **kwargs):
    cur = con.cursor()
    cur.execute(insert_into_venv_info_sql, (kwargs['project_path'], kwargs['venv_name'], kwargs['created_date'], kwargs['requirement_file'], kwargs['connect_status'], kwargs['last_modified']))
    con.commit()

def update_data_venv_info(con: sqlite3.Connection, *args, **kwargs):
    cur = con.cursor()
    cur.execute(update_connect_status_venv_info_sql, (kwargs['connect_status'], kwargs['last_modified'], kwargs['venv_name']))
    con.commit()


def check_venv_connection(con: sqlite3.Connection, system_control: types.ModuleType, *args, **kwargs):
    cur = con.cursor()
    result = cur.execute(select_all_venv_view)
    venv_info = result.fetchall()
    for i in range(len(venv_info)):
        venv_name, _, connect_status, project_path, _ = venv_info[i]
        code_status = system_control.activate_venv(project_path, venv_name)
        if code_status != 0 and connect_status != get_color_str('no', 'RED'):
            update_data_venv_info(con, connect_status = get_color_str('no', 'RED'), venv_name = venv_name, last_modified = datetime.now())

