import os
import shutil

from compressor.base import Compressor
from django.conf import settings
import pytest


COMPRESSOR_HASH = 'test-hash'


def pytest_configure():
    shutil.rmtree(settings.COMPRESS_ROOT, ignore_errors=True)


@pytest.fixture(autouse=True)
def fake_compressor_filename(monkeypatch):
    monkeypatch.setattr('compressor.base.get_hexdigest', lambda text, length: COMPRESSOR_HASH)


@pytest.fixture
def precompiled():
    """
    Fixture that does the following steps:

    - searches given static file, e.g. 'app/layout.scss'
    - finds corresponding pre-compiled file generated by ``django-compressor``
    - returns pre-compiled file contents

    Usage:

        assert precompiled('app/layout.scss', 'css') == '.title {\n  font-size: 30px;\n}\n'
    """
    def runner(original_file_path, file_type):
        """
        :param original_file_path: e.g. 'app/layout.scss'
        :param file_type: 'css' or 'js'
        """
        original_file_name = os.path.basename(original_file_path)
        compiled_file_path = os.path.join(
            settings.COMPRESS_ROOT,
            Compressor(output_prefix=file_type).get_filepath('...', original_file_name)
        )
        with open(compiled_file_path) as f:
            return f.read()
    return runner
