import csv
from dataclasses import dataclass, field


@dataclass
class FilterConfig:
    name: str
    text: str
    filter_type: str
    width: str
    key_column: str
    value_column: str
    sort_column: str
    visible: bool = True
    default_value: str = ""
    options: dict[str, str] | None = field(default_factory=dict)
    current_value: str | None = None

    @property
    def query_param(self) -> str:
        if self.current_value is None or self.current_value == "":
            if self.default_value is None or self.default_value == "":
                return None
            self.current_value = self.default_value

        if self.filter_type == "date":
            if "bis" in self.name.lower():
                return f" F.[{self.key_column}] <= '{self.current_value}' "
            return f" F.[{self.key_column}] >= '{self.current_value}' "
        # if self.filter_type == "select":
        #     return f"{self.key_column} IN ({self.current_value})"
        return f" F.[{self.key_column}] LIKE '%{self.current_value}%' "

    @staticmethod
    def from_dict(
        name: str,
        filter_type: str,
        width: str,
        text: str,
        key_column: str,
        value_column: str,
        sort_column: str,
        default_value: str,
    ) -> "FilterConfig":
        if filter_type not in ["text", "select", "date", "hidden"]:
            filter_type = "text"
        if width not in ["1", "2", "3", "4"]:
            width = "2"
        if not text:
            text = name
        if not key_column:
            key_column = name
        if not value_column:
            value_column = key_column
        if not sort_column:
            sort_column = key_column
        if not default_value:
            default_value = ""

        return FilterConfig(
            name=name,
            text=text,
            filter_type=filter_type,
            width=width,
            key_column=key_column,
            value_column=value_column,
            sort_column=sort_column,
            default_value=default_value,
        )


filter_type_option = {
    "text": "text",
    "select": "selectedOptionValue",
    "date": "selectedDate",
    "hidden": "selectedOptionValue",
}


def import_filter_config(area: str) -> list[FilterConfig]:
    res = []
    with open(f"templates\\{area}\\liste\\config\\liste_filter.csv", "r", newline="", encoding="latin-1") as csvfile:
        reader = csv.DictReader(csvfile, delimiter=";")
        for row in reader:
            config = FilterConfig.from_dict(*row.values())

            res.append(config)
    return res
