from dataclasses import dataclass
from typing import Union, List, Optional, Type

from ..elements.table_base import TableBase
from ..exceptions import MultipleTypesInOneAction
from ..statements.abstract_statement import AbstractStatement


@dataclass
class Insert(AbstractStatement):
    values: Union[TableBase, List[TableBase]]

    def generate_sql(self) -> str:
        if not isinstance(self.values, list):
            self.values = [self.values]

        sql = ""
        params = []

        table: Optional[Type[TableBase]] = None
        for value in self.values:
            if table is None:
                table = type(value)
                sql = f'INSERT INTO {self.database}.{table.get_name()} ({", ".join(value.to_insert_columns())}) VALUES '
            elif table != type(value):
                raise MultipleTypesInOneAction(f"Got {repr(self.values)}")
            params.append(tuple(value.to_insert_data()))

        sql += ", ".join(["%s"] * len(params))
        sql = sql % tuple(params)
        return sql

    def form_result(self, payload: str):
        ...
