from devices.models.endpoint_device import EndpointModel
from devices.services.endpoint.endpoint_redis import RedisInterface


def get_status(request, pk: int) -> dict:
    """ Function to respond with current Endpoint states. Current response states are:
        config_errors,
        request_config
    :param request: request instance
    :param pk: Corresponding Endpoint pk
    :return: JSON response with endpoint configuration errors
    """
    try:
        endpoint = EndpointModel.objects.get(pk=pk)
    except EndpointModel.DoesNotExist:
        return {'status': 'error', 'reason': 'no such endpoint record'}
    return {
        'endpoint_config_errors': endpoint.config_errors,
        'is_requested_config_correct': endpoint.is_requested_config_correct
    }


class EndpointStatusService:
    """Service return endpoint connect status"""

    def __init__(self, endpoint: EndpointModel):
        if isinstance(endpoint, EndpointModel):
            self.endpoint = endpoint
        else:
            self.endpoint = EndpointModel.objects.get(pk=endpoint.pk)
        self.redis = RedisInterface()

    def get_status(self) -> dict:
        endpoint_status = {}
        if self.redis.get_keepalive(self.endpoint.pk):
            if self.endpoint.config_errors:
                endpoint_status['status'] = 'config_errors'
                endpoint_status['config_errors'] = self.endpoint.incorrect_settings
            else:
                endpoint_status['status'] = 'online'
        else:
            endpoint_status['status'] = 'offline'
        return endpoint_status
