import pymssql
import configparser

class MSSQLDatabase:
    def __init__(self):
        self.conn = None
        self.server = None
        self.database = None
        self.username = None
        self.password = None

    def connect(self, config_path):
        """
        Connect to the database using a config file.

        Parameters:
            config_path (str): Path to config.ini with credentials.
        """
        try:
            config = configparser.ConfigParser()
            config.read(config_path)

            self.server = config["database"]["server"]
            self.database = config["database"]["database"]
            self.username = config["database"]["username"]
            self.password = config["database"]["password"]

            self.conn = pymssql.connect(
                server=self.server,
                user=self.username,
                password=self.password,
                database=self.database
            )

            print("Connection successful!")

        except Exception as e:
            print("Error connecting to the database:", e)

    def disconnect(self):
        """
        Close the active database connection.
        """
        try:
            if self.conn:
                self.conn.close()
                self.conn = None
                print("Disconnected from the database.")
            else:
                print("No active connection to disconnect.")
        except Exception as e:
            print("Error disconnecting from the database:", e)


    def listTables(self):
        """
        List all base tables in the database.
        """
        if not self.conn:
            print("Not connected to the database.")
            return

        try:
            cursor = self.conn.cursor()
            query = """
            SELECT TABLE_NAME
            FROM INFORMATION_SCHEMA.TABLES
            WHERE TABLE_TYPE = 'BASE TABLE'
            """
            cursor.execute(query)
            tables = cursor.fetchall()

            print("Tables in the database:")
            for table in tables:
                print(table[0])
        except Exception as e:
            print("Error fetching tables:", e)

    def showTableStructure(self, table_name):
        """
        Show column structure of a table.

        Parameters:
            table_name (str): Table name.
        """
        if not self.conn:
            print("Not connected to the database.")
            return

        try:
            cursor = self.conn.cursor()
            query = """
            SELECT COLUMN_NAME, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH
            FROM INFORMATION_SCHEMA.COLUMNS
            WHERE TABLE_NAME = %s
            """
            cursor.execute(query, (table_name,))
            columns = cursor.fetchall()

            print(f"Structure of the table '{table_name}':")
            print(f"{'Column Name':<30} {'Data Type':<15} {'Max Length'}")
            print("=" * 60)

            for column in columns:
                column_name, data_type, max_length = column
                max_length = max_length if max_length is not None else ''
                print(f"{column_name:<30} {data_type:<15} {max_length}")

        except Exception as e:
            print(f"Error fetching structure of table '{table_name}':", e)

    def showTableData(self, table_name):
        """
        Display all data from a table.

        Parameters:
            table_name (str): Table name.
        """
        if not self.conn:
            print("Not connected to the database.")
            return

        try:
            cursor = self.conn.cursor()
            query = f"SELECT * FROM {table_name}"
            cursor.execute(query)

            rows = cursor.fetchall()
            columns = [column[0] for column in cursor.description]

            print(f"Data in the table '{table_name}':")
            print(columns)

            for row in rows:
                print(row)

        except Exception as e:
            print(f"Error fetching data from table '{table_name}':", e)

    def getData(self, table, pn, sn):
        """
        Get rows filtered by pn and sn.

        Parameters:
            table (str): Table name (must be allowed).
            pn: Part number filter.
            sn: Serial number filter.

        Returns:
            list | None: Matching rows, empty list, or None on error.
        """
        if not self.conn:
            print("Not connected to the database.")
            return None

        try:
            # Optional but strongly recommended: whitelist tables
            allowed_tables = [
                "NewView7100",
                "ASI",
                "Radii",
                "sysdiagrams",
                "OWI",
                "OWI_vyr",
                "diameter",
                "thickness"
                ]
            if table not in allowed_tables:
                raise ValueError("Invalid table name")

            cursor = self.conn.cursor(as_dict=True)

            query = f"""
                SELECT *
                FROM {table}
                WHERE pn = %s AND sn = %s
            """

            cursor.execute(query, (pn, sn))
            rows = cursor.fetchall()

            if rows:
                print(f"{len(rows)} record(s) found for pn='{pn}', sn='{sn}'")
                return rows
            else:
                print(f"No records found for pn='{pn}', sn='{sn}'")
                return []

        except Exception as e:
            print(f"Error fetching data for pn='{pn}', sn='{sn}':", e)
            return None
