import logging
import os

from rest_framework import status
from rest_framework.response import Response

from inputs.constants import LOGSTASH_CONFIG_DIR
from inputs.models import LogInput

_log = logging.getLogger(__name__)


def delete_input(kwargs):
    try:
        log_input = LogInput.objects.get(pk=kwargs.get('pk'))
        if log_input.config_file_name:
            log_input.delete()
            try:
                os.remove(os.path.join(LOGSTASH_CONFIG_DIR,
                                       log_input.config_file_name))
                _log.info(f'Removed file [{log_input.config_file_name}]')
                return Response(status=status.HTTP_200_OK)
            except IOError:
                _log.warning(
                    f'Try to remove log input pk {log_input.pk} but file {log_input.config_file_name} does not exist')
                return Response(status=status.HTTP_417_EXPECTATION_FAILED)

    except LogInput.DoesNotExist:
        _log.error(f"Loginput with pk {kwargs.get('pk')} did not find")
        return Response(status=status.HTTP_404_NOT_FOUND)
