import pytest

from fidere import JsonSchemaParser
from fidere.meta import MANDATORY_DEVICE_FIELDS, MANDATORY_ENTITY_FIELDS
from fidere.models import NormalizedModel


class TestGeneral:
    """Only for testing VERY simple tasks"""

    def test_instancing(self):
        """Test simple instancing. If this fails, things are heavily screwed up!"""
        parser = JsonSchemaParser()
        assert isinstance(parser, JsonSchemaParser)
        with JsonSchemaParser() as parser:
            assert isinstance(parser, JsonSchemaParser)

    def test_finding_mandatory_entity_fields(
        self, path_schema, entity_instance
    ):
        """Test to check if missing mandatory fields are found"""
        instance = entity_instance
        parser = JsonSchemaParser()
        id_ = parser.parse_schema(
            schema=path_schema, model_class=NormalizedModel
        )

        # Test for catching missing mandatory fields
        temp = {
            key: instance[key]
            for key in instance
            if key not in MANDATORY_ENTITY_FIELDS
        }
        with pytest.raises(KeyError):
            parser.create_context_entity(instance.fromkeys(temp), id_)

    def test_finding_mandatory_device_fields(
        self, path_schema, device_instance
    ):
        """Test to check if missing mandatory fields are found"""
        instance = device_instance
        parser = JsonSchemaParser()
        id_ = parser.parse_schema(
            schema=path_schema, model_class=NormalizedModel
        )

        # Test for catching missing mandatory fields
        temp = {
            key: instance[key]
            for key in instance
            if key not in MANDATORY_DEVICE_FIELDS
        }
        with pytest.raises(KeyError):
            parser.create_device(instance.fromkeys(temp), id_)

    def test_valid_schema_location(self, path_schema):
        """Test if the schema location is correctly identified"""
        with JsonSchemaParser() as parser:
            parser.parse_schema(
                schema=path_schema, model_class=NormalizedModel
            )

    def test_invalid_schema_location(self):
        """Test invalid schema location handling"""
        with JsonSchemaParser() as parser:
            with pytest.raises(ValueError):
                parser.parse_schema(
                    schema="W:/this/is/not/a/file.json",
                    model_class=NormalizedModel,
                )
            with pytest.raises(ValueError):
                parser.parse_schema(
                    schema="https://invalid-url.xyz/get/stuff.json",
                    model_class=NormalizedModel,
                )
