import os
import struct
import pyodbc
from azure.identity import DefaultAzureCredential


'''
Requirements:
    - pyodbc
    - azure-identity
Requires several system libraries:
unixodbc:
  mac:
      - brew install unixodbc
  redhat:
      - yum install unixODBC
  windows:
      - windows - maybe install with instructions at
        https://learn.microsoft.com/en-us/sql/connect/odbc/download-odbc-driver-for-sql-server?view=sql-server-ver17
'''


def fetch(connection=None, source=None, **kwargs):
    credential = DefaultAzureCredential(
        exclude_interactive_browser_credential=False
    )

    token_bytes = credential.get_token(
        'https://database.windows.net/.default'
    ).token.encode('UTF-16-LE')

    token_struct = struct.pack(
        f'<I{len(token_bytes)}s', len(token_bytes), token_bytes
    )

# This connection option is defined by microsoft in msodbcsql.h
    SQL_COPT_SS_ACCESS_TOKEN = 1256

    driver = '{ODBC Driver 18 for SQL Server}'
    HOST = connection.params['FABRIC_HOST']
    DATABASE = connection.params['FABRIC_DATABASE']
    PORT = connection.params.get('FABRIC_PORT', 1433)
    ENCRYPT = connection.params.get('FABRIC_ENCRYPT', 'yes')
    # DATABASE = 'DWTest'

    connection_string = (
        f'DRIVER={driver};'
        f'SERVER={HOST};'
        f'PORT={PORT};'
        f'DATABASE={DATABASE};'
        f'ENCRYPT={ENCRYPT};'
        'Trusted_Connection=no;'
        'Connection Timeout=30'
    )

    conn = pyodbc.connect(
        connection_string, attrs_before={SQL_COPT_SS_ACCESS_TOKEN: token_struct}
    )
    cursor = conn.cursor()

    query = source.params['query']
    cursor.execute(query)

    return cursor
