# application/db/inverter_queries.py

from application.db.query_executor import QueryResults
# from application.db import Database
# from application.auth.decorators import query_executor
import traceback
from flask import current_app
class InverterQueries:

    def save_inverter_details(self, username, password, inverter_id, user_id):
        try:
            insert_query = {
                'statement': """
                    INSERT INTO inverter_details (username, password, user_id, inverter_provider) 
                    VALUES (%s, %s, %s, %s)
                """,
                'params': (username, password, user_id, inverter_id,)
            }
            query_results = current_app.extensions['query_results']

            rows_affected = query_results.insertion(commit=True, **insert_query)
            return rows_affected > 0  # True if insertion was successful
        except Exception as e:
            # log error here
            print(traceback.print_exc())
            raise e

    def check_inverter_exists(self, user_id):
        try:
            select_query = {
                'statement': "SELECT * FROM inverter_details WHERE {} = %s",
                "column_name": ('user_id',),
                'params': (user_id,)
            }
            query_results = current_app.extensions['query_results']
            user_result = query_results.fetch_query_results(**select_query)

            if not user_result:
                return True
            return False
        except Exception as e:
            # log error here
            print(traceback.print_exc())
            raise e

    def get_inverter_list(self):
        try:
            select_query = {
                'statement': "SELECT id , provider_name FROM inverter_provider",
                "column_name": (),
                'params': ()
            }
            query_results = current_app.extensions['query_results']
            user_result = query_results.fetch_query_results(**select_query)

            return user_result
        except Exception as e:
            # log error here
            print(traceback.print_exc())
            raise e

    def update_inverter_credentials(self, username, password, inverter_id, user_id):
        try:
            update_query = {
                'statement': """
                    UPDATE inverter_details 
                    SET username = %s, password = %s, inverter_provider = %s 
                    WHERE user_id = %s
                """,
                'params': (username, password, inverter_id, user_id)
            }
            query_results = current_app.extensions['query_results']
            rows_affected = query_results.updation(commit=True, **update_query)
            return True  # True if update was successful
        except Exception as e:
            # log error here
            raise e
