import mysql.connector

class Mysql:
    def __init__(self, app):
        self.host = app.config['MYSQL_HOST']
        self.user = app.config['MYSQL_USER']
        self.password = app.config['MYSQL_PASSWORD']
        self.database = app.config['MYSQL_DB']
        self.connection = None

        self.connect()

    def connect(self):
        try:
            self.connection = mysql.connector.connect(
                host=self.host,
                user=self.user,
                password=self.password,
                database=self.database,
            )
        except mysql.connector.Error as err:
            print(f"Error connecting to MySQL: {err}")

    def execute_query(self, sql, bind_params=None, columns=None, one_result=False):
        try:
            with self.connection.cursor() as cursor:
                if bind_params:
                    cursor.execute(sql, bind_params)
                else:
                    cursor.execute(sql)

                if one_result is False:
                    result_rows = cursor.fetchall()
                    result = []
                    for result_row in result_rows:
                        result_obj = dict(zip(columns, result_row))
                        result.append(result_obj)
                    return result
                else:
                    result = cursor.fetchone()  # Retorna apenas um resultado
                    result_obj = dict(zip(columns, result))
                    return result_obj
        except mysql.connector.OperationalError as err:
            print(f"OperationalError: {err}")
            print("Attempting to reconnect...")
            self.connect()
            return self.execute_query(sql, bind_params, columns, one_result)
        except mysql.connector.Error as err:
            print(f"Error executing query: {err}")
        return None