from unittest.mock import patch

import pytest

from devices.models.endpoint_device import EndpointModel
from inputs.enums import LogInputType
from inputs.models import LogInput, LogInputArmaIF, LogInputEndpoint
from inputs.serializers import InputSerializer
from inputs.enums import SensorType, SensorScheme
from devices.models.sensor import ArmaSensor

TEST_PORTS = (
    (5000, False),
    (5001, False),
    (5002, True),
)

SENSOR_DATA = {
    "name": "SENSOR_TEST",
    "ip": "1.1.1.1",
    "port": 5000,
    "type": 'firewall'
}


@pytest.mark.django_db
@patch('django.conf.settings.LOGSTASH_CONFIG_DIR', '/tmp')
class TestLogInputSerializer:

    @pytest.fixture(autouse=True)
    def setup_test(self) -> None:
        test_sensor = ArmaSensor.objects.create(**SENSOR_DATA)
        test_input = LogInput.objects.create(label='test_input', type=LogInputType.ARMAIF)
        LogInputArmaIF.objects.create(input=test_input, port=5000, sensor=test_sensor)

        endpoint = EndpointModel.objects.create(
            name='Test endpoint to copy',
            description='Description',
            ip='1.2.3.4',
            port=5555,
            integrity_control_enabled=False,
            whitelist_enabled=True,
            device_control_enabled=True,
            prohibit_cd_access=True,
            usb_control_enabled=True
        )
        log_input = LogInput.objects.create(label=endpoint.name, type=LogInputType.ENDPOINT, can_delete=False)
        LogInputEndpoint.objects.create(endpoint=endpoint, input=log_input, port=5001)

    @pytest.mark.unit
    @pytest.mark.parametrize('port, is_valid', TEST_PORTS)
    def test_log_input_armaif_serializer(self, port: int, is_valid: bool):
        data = {'port': port, 'type': 'armaif', 'label': 'label'}
        serializer = InputSerializer(data=data)

        assert serializer.is_valid() == is_valid
        if not is_valid:
            assert 'port' in serializer.errors
            assert 'This port is already in use' in serializer.errors['port']

    @pytest.mark.unit
    @pytest.mark.parametrize('port, is_valid', TEST_PORTS)
    def test_log_input_endpoint_form(self, port: int, is_valid: bool):
        data = {'port': port, 'type': 'endpoint', 'label': 'label'}
        serializer = InputSerializer(data=data)
        assert serializer.is_valid() == is_valid
        if not is_valid:
            assert 'port' in serializer.errors
            assert 'This port is already in use' in serializer.errors['port']
