from datetime import datetime

from dateutil.relativedelta import relativedelta

from feedrsub.database import db
from feedrsub.models.period import PERIOD, Period
from feedrsub.models.populate_db import populate_periods


def test_populate_periods(session):
    populate_periods()

    daily = Period.query.filter_by(name=PERIOD.DAILY).first()
    assert daily.name == PERIOD.DAILY

    immediate = Period.query.filter_by(name=PERIOD.IMMEDIATE).first()
    assert immediate.name == PERIOD.IMMEDIATE

    weekly = Period.query.filter_by(name=PERIOD.WEEKLY).first()
    assert weekly.name == PERIOD.WEEKLY

    monthly = Period.query.filter_by(name=PERIOD.MONTHLY).first()
    assert monthly.name == PERIOD.MONTHLY


def test_period_creation(session):
    period_desc = "A Yearly period"
    period_name = "YEARLY"
    period = Period(period_name, period_desc)
    db.session.add(period)
    db.session.commit()

    yearly = Period.query.filter_by(name=period_name).first()
    assert yearly.name == period_name
    assert yearly.description == period_desc


def test_get_from_date_with_name(session):
    now = datetime.utcnow()
    past = now - relativedelta(days=1)

    from_date = Period.get_from_date(PERIOD.DAILY, now)
    assert from_date == past


def test_get_from_date_with_period(session):
    now = datetime.utcnow()
    past = now - relativedelta(days=1)

    period = Period(name=PERIOD.DAILY)
    from_date = Period.get_from_date(period, now)
    assert from_date == past
