from typing import Iterable, Mapping, Optional, Union

from airflow.models import BaseOperator
from airflow.models.connection import Connection
from airflow.utils.decorators import apply_defaults

from twitch_airflow_components.hooks.postgres import PostgresHook


class PostgresOperator(BaseOperator):
    """
    Executes sql code in a specific Postgres database. Different from the
    airflow PostgresOperator in that it accepts a full connection object
    rather than a connection ID.
    :param sql: the sql code to be executed. (templated)
    :type sql: Can receive a str representing a sql statement,
        a list of str (sql statements), or reference to a template file.
        Template reference are recognized by str ending in '.sql'
    :param connection: reference to a specific postgres database
    :type connection: airflow.models.connection.Connection
    :param autocommit: if True, each command is automatically committed.
        (default value: False)
    :type autocommit: bool
    :param parameters: (optional) the parameters to render the SQL query with.
    :type parameters: dict or iterable
    :param database: name of database which overwrite defined one in connection
    :type database: str
    """

    template_fields = ("sql",)
    template_fields_renderers = {"sql": "sql"}
    template_ext = (".sql",)
    ui_color = "#ededed"

    @apply_defaults
    def __init__(
        self,
        *,
        sql: str,
        connection: Connection,
        autocommit: bool = False,
        parameters: Optional[Union[Mapping, Iterable]] = None,
        database: Optional[str] = None,
        **kwargs,
    ) -> None:
        super().__init__(**kwargs)
        self.sql = sql
        self.connection = connection
        self.autocommit = autocommit
        self.parameters = parameters
        self.database = database
        self.hook = PostgresHook(connection=self.connection, schema=self.database)
        # self.hook = None

    def execute(self, context):
        self.log.info("Executing: %s", self.sql)
        # self.hook = PostgresHook(connection=self.connection, schema=self.database)
        self.hook.run(self.sql, self.autocommit, parameters=self.parameters)
        for output in self.hook.conn.notices:
            self.log.info(output)
