from datetime import datetime, timedelta

import Models
from app import db

start = datetime(year=2022, month=4, day=7)


def todays_analytics():
    return get_analytics(datetime.utcnow().date())


def yesterdays_analytics():
    return get_analytics((datetime.utcnow()-timedelta(days=1)).date())


def get_analytics(date):
    day = AnalyticsModel.query.get(date)
    if not day:
        if date > start.date():
            day = AnalyticsModel(date=date)
            db.session.add(day)
            db.session.commit()
        else:
            day = AnalyticsModel.query.get(datetime.min.date())
            if not day:
                day = AnalyticsModel(date=datetime.min.date())
                db.session.add(day)
                db.session.commit()
    return day


class AnalyticsModel(Models.Base):
    __tablename__ = 'analytics'

    date = db.Column(db.DateTime, primary_key=True, default=datetime.today().date())
    register_count = db.Column(db.Integer, nullable=False, default=0)
    active_user_count = db.Column(db.Integer, nullable=False, default=0)
    post_count = db.Column(db.Integer, nullable=False, default=0)
    likes_count = db.Column(db.Integer, nullable=False, default=0)
    dislikes_count = db.Column(db.Integer, nullable=False, default=0)
    matches_count = db.Column(db.Integer, nullable=False, default=0)
    projects_count = db.Column(db.Integer, nullable=False, default=0)

    def __init__(self, **kwargs):
        self.date = datetime.today().date()
        super().__init__(**kwargs)
