"""
    Tests for the CSScheme dumper
"""

import pytest

from ..tinycss.css21 import Stylesheet, Declaration, RuleSet
from ..tinycss.token_data import Token
from ..tinycss.tokenizer import tokenize_grouped

from .. import dumper
from ..dumper import DumpError
from ..parser import StringRule

from . import jsonify


# Shorthand functions for tinycss classes
def T(type_, value):  # noqa
    return Token(type_, value, value, None, 0, 0)


def SR(keyword, value):  # noqa
    tokens = list(tokenize_grouped(value))
    assert len(tokens) == 1
    return StringRule(keyword, tokens[0], 0, 0)


def SS(rules):  # noqa
    return Stylesheet(rules, [], None)


def RS(sel, decl, at_rules=[]):  # noqa
    sel = tokenize_grouped(sel)
    rs = RuleSet(sel, decl, 0, 0)
    rs.at_rules = at_rules
    return rs


def DC(name, value):  # noqa
    return Declaration(name, tokenize_grouped(value), None, 0, 0)


@pytest.mark.parametrize(('stylesheet', 'expected_data'), [
    (SS([SR('@name', "Test"),
         SR('@at-rule', "hi"),
         RS('*', []),
         # Should this be tested here?
         RS('source', [DC('foreground', "#123456")]),
         SR('@uuid', '2e3af29f-ebee-431f-af96-72bda5d4c144')
         ]),
     {'name': "Test",
      'at-rule': "hi",
      'uuid': "2e3af29f-ebee-431f-af96-72bda5d4c144",
      'settings': [
          {'settings': {}},
          {'scope': "source",
           'settings': {'foreground': "#123456"}},
      ]}
     ),
])
def test_datafy(stylesheet, expected_data):
    data = dumper.datafy_stylesheet(stylesheet)
    assert data == expected_data


@pytest.mark.parametrize(('stylesheet', 'expected_error'), [
    (SS([SR('@name', "Test"),
         ]),
     "Must contain '*' ruleset"
     ),

    (SS([SR('@name', "Test"),
         RS('*', []),
         RS('*', [])
         ]),
     "Only one *-rule allowed"
     ),

    (SS([SR('@settings', "value"),
         SR('@name', "Test"),
         RS('*', [])
         ]),
     "Can not override 'settings' key using at-rules."
     ),
])
def test_datafy_errors(stylesheet, expected_error):
    try:
        dumper.datafy_stylesheet(stylesheet)