import pytest

from datetime import datetime, timedelta

from dms_influx2.utils import localize_dt


BUCKET = 'test_bucket_stats'
DEVICE_ID = 'devstats.ch'
DESCRIPTION = 'stats test'


@pytest.fixture
def init_stats(client):
    now = localize_dt(datetime.utcnow())
    data = {
        'device_id': DEVICE_ID,
        'description': DESCRIPTION,
        'values': [
            (now - timedelta(minutes=3), 1.0),
            (now - timedelta(minutes=2), 2.0),
            (now - timedelta(minutes=1), 3.0),
        ],
    }
    client.save_data(bucket=BUCKET, data=data)


def test_get_device_stats(init_stats, client):
    stats = client.get_device_stats(bucket=BUCKET, device_id=DEVICE_ID, description=DESCRIPTION)

    assert stats['device'] == 'devstats'
    assert stats['device_id'] == DEVICE_ID

    assert stats['min_day'] == 1.0
    assert stats['max_day'] == 3.0
    assert stats['avg_day'] == 2.0

    assert stats['min_month'] == 1.0
    assert stats['max_month'] == 3.0
    assert stats['avg_month'] == 2.0

    assert stats['min_year'] == 1.0
    assert stats['max_year'] == 3.0
    assert stats['avg_year'] == 2.0

    assert stats['min_last_30_days'] == 1.0
    assert stats['max_last_30_days'] == 3.0
    assert stats['avg_last_30_days'] == 2.0


def test_get_device_stats_empty(client):
    client.buckets_api().create_bucket_if_not_exists(bucket_name=BUCKET)
    stats = client.get_device_stats(bucket=BUCKET, device_id='nope.ch')

    assert stats['min_day'] is None
    assert stats['max_day'] is None
    assert stats['avg_day'] is None

    assert stats['min_month'] is None
    assert stats['max_month'] is None
    assert stats['avg_month'] is None

    assert stats['min_year'] is None
    assert stats['max_year'] is None
    assert stats['avg_year'] is None

    assert stats['min_last_30_days'] is None
    assert stats['max_last_30_days'] is None
    assert stats['avg_last_30_days'] is None
