from .database import DatabaseController
from models.stats import Stats


class StatsController(DatabaseController):
    FIELDS = ['id', 'userID', 'productID', 'viewDate']

    def __init__(self):
        super().__init__()

    def create(self, view: Stats):
        params = [
            view.userID,
            view.productID,
            view.viewDate
        ]

        self._conn.execute(
            """
            INSERT INTO Views
            (userID, productID, viewDate)
            VALUES (?, ?, ?)""",
            params
        )
        self._conn.commit()

    def read(self) -> list[Stats] | None:

        cursor = self._conn.execute(
            "SELECT * FROM Views",
        )
        rows = cursor.fetchmany()

        if rows is None:
            return None

        views = list()

        # Create an object for each row
        for view in rows:
            params = dict(zip(self.FIELDS, view))
            obj = self.new_instance(Stats, params)
            views.append(obj)

        return views

    def read_product(self, product_id: int = 0) -> list[Stats] | None:
        params = [
            product_id
        ]

        cursor = self._conn.execute(
            """SELECT * FROM Views
            WHERE productID = ?
            """,
            params
        )
        rows = cursor.fetchall()

        if len(rows) == 0:
            return None

        views = list()

        # Create an object for each row
        for view in rows:
            params = dict(zip(self.FIELDS, view))
            obj = self.new_instance(Stats, params)
            views.append(obj)

        return views

    def read_user(self, user_id: int) -> list[Stats] | None:
        params = [
            user_id
        ]

        cursor = self._conn.execute(
            """SELECT * FROM Views
            WHERE userID = ?
            """,
            params
        )
        rows = cursor.fetchall()

        if len(rows) == 0:
            return None

        views = list()

        # Create an object for each row
        for view in rows:
            params = dict(zip(self.FIELDS, view))
            obj = self.new_instance(Stats, params)
            views.append(obj)

        return views

    def update(self):
        print("Doing work")

    def delete(self):
        print("Doing work")
