from fanstatic import Library, Resource, NeededResources
from fanstatic import compat, Inclusion, MINIFIED
from fanstatic import set_resource_file_existence_checking
from fanstatic.compiler import Compiler, Minifier
from .test_checksum import _copy_testdata
from zipfile import ZipFile
import fanstatic
import fanstatic.compiler
import os
import pytest
import subprocess
import sys
import time


class MockCompiler(fanstatic.compiler.Compiler):

    name = 'mock'
    source_extension = '.source'
    available = True

    def __init__(self):
        self.calls = []

    def __call__(self, resource, force=False):
        self.calls.append(resource)


class MockMinifier(fanstatic.compiler.Minifier):

    name = 'mock'
    target_extension = '.min.js'
    available = True

    def __init__(self):
        self.calls = []

    def __call__(self, resource, force=False):
        self.calls.append(resource)


class TestingRegistry(object):

    def __init__(self, request):
        self.request = request

    def add_compiler(self, compiler):
        return self._register_compiler(
            fanstatic.CompilerRegistry, compiler)

    def add_minifier(self, compiler):
        return self._register_compiler(
            fanstatic.MinifierRegistry, compiler)

    def _register_compiler(self, registry, compiler):
        self.request.addfinalizer(
            lambda: registry.instance().pop(compiler.name))
        registry.instance().add(compiler)
        return compiler

    def compiler(self, name):
        return fanstatic.CompilerRegistry.instance()[name]

    def minifier(self, name):
        return fanstatic.MinifierRegistry.instance()[name]


@pytest.fixture
def compilers(request):
    return TestingRegistry(request)



def test_logging_when_compiling(tmpdir, compilers, caplog):
    class WhiteSpaceRemover(fanstatic.compiler.Compiler):
        """A silly minifier, to showcase logging."""
        name = 'whitespace'
        source_extension = '.frop'

        def process(self, source, target):
            with open(target, 'wb') as output:
                output.write(compat.as_bytestring(
                    open(source, 'r').read().replace(' ', '')))

    compilers.add_compiler(WhiteSpaceRemover())

    lib = Library('lib', str(tmpdir))
    tmpdir.join('a.frop').write(' foo bar baz ')
    a = Resource(lib, 'a.js', compiler='whitespace')
    assert len(caplog.records()) == 0
    a.compile()
    assert len(caplog.records()) == 1
    assert "Compiling <Resource 'a.js' in library 'lib'> in" in caplog.text()
    # The 'compiler' really worked!
    assert tmpdir.join('a.js').read() == 'foobarbaz'


def test_compile_only_for_libraries_under_development(
    compilers):
    compilers.add_compiler(MockCompiler())

    lib = Library('lib', '')