from .connections import DatabaseConnection
class QuerySet:
    
    def __init__(self, model_cls):
        self.model_cls = model_cls
        self._filters = {}
        self._limit = None

    def all(self):
        return self    

    def filter(self, **kwargs):
        qs = QuerySet(self.model_cls)
        qs._filters = {**self._filters, **kwargs}
        return qs
    
    def get(self, **kwargs):
        qs = self.filter(**kwargs)

        results = list(qs)

        if len(results) == 0:
            raise Exception("DoesNotExist")

        if len(results) > 1:
            raise Exception("MultipleObjectsReturned")

        return results[0]


    def _build_where(self):
        if not self._filters:
            return '', []
        conditions = []
        values = []
        for field, value in self._filters.items():
            op = "="
            fname = field
            if '__gt' in field:
                fname = field.replace('__gt', '')
                op = ">"
            elif '__lt' in field:
                fname = field.replace('__lt', '')
                op = "<"
            # add more operators later: __gte, __lte, __contains, etc.

            conditions.append(f'"{fname}" {op} %s')
            values.append(value)

        return f"WHERE {' AND '.join(conditions)}", values

    def __iter__(self):
        conn = DatabaseConnection.get_connection()
        where, values = self._build_where()
        query = f'SELECT * FROM "{self.model_cls._table_name}" {where}'
        cursor = conn.execute(query, values)
        rows = cursor.fetchall()
        for row in rows:
            yield self.model_cls(**row)