import pytest

from datetime import timedelta

from django.conf import settings as conf
from django.utils import timezone as tz

from aircox import models
from aircox.controllers.sound_file import SoundFile


@pytest.fixture
def path_infos():
    return {
        "test/20220101_10h13_1_sample_1.mp3": {
            "year": 2022,
            "month": 1,
            "day": 1,
            "hour": 10,
            "minute": 13,
            "n": 1,
            "name": "Sample 1",
        },
        "test/20220102_10h13_sample_2.mp3": {
            "year": 2022,
            "month": 1,
            "day": 2,
            "hour": 10,
            "minute": 13,
            "name": "Sample 2",
        },
        "test/20220103_1_sample_3.mp3": {
            "year": 2022,
            "month": 1,
            "day": 3,
            "n": 1,
            "name": "Sample 3",
        },
        "test/20220104_sample_4.mp3": {
            "year": 2022,
            "month": 1,
            "day": 4,
            "name": "Sample 4",
        },
        "test/20220105.mp3": {
            "year": 2022,
            "month": 1,
            "day": 5,
            "name": "20220105",
        },
    }


@pytest.fixture
def sound_files(path_infos):
    return {k: r for k, r in ((path, SoundFile(conf.MEDIA_ROOT + "/" + path)) for path in path_infos.keys())}


def test_sound_path(sound_files):
    for path, sound_file in sound_files.items():
        assert path == sound_file.sound_path


def test_read_path(path_infos, sound_files):
    for path, sound_file in sound_files.items():
        expected = path_infos[path]
        result = sound_file.read_path(path)
        # remove None values
        result = {k: v for k, v in result.items() if v is not None}
        assert expected == result, "path: {}".format(path)


def _setup_diff(program, info):
    episode = models.Episode(program=program, title="test-episode")
    at = tz.datetime(**{k: info[k] for k in ("year", "month", "day", "hour", "minute") if info.get(k)})
    at = tz.make_aware(at)
    diff = models.Diffusion(episode=episode, start=at, end=at + timedelta(hours=1))
    episode.save()
    diff.save()
    return diff


@pytest.mark.django_db(transaction=True)
def test_find_episode(sound_files):
    station = models.Station(name="test-station")
    program = models.Program(station=station, title="test")
    station.save()
    program.save()

    for path, sound_file in sound_files.items():
        infos = sound_file.read_path(path)
        diff = _setup_diff(program, infos)
        sound = models.Sound(program=diff.program, file=path)
        result = sound_file.find_episode(sound, infos)
        assert diff.episode == result

    # TODO: find_playlist, sync
