import sys
import ast

import werkzeug.exceptions

from blackant.utils.logging import get_logger
from task.parsers.base import RequestParserBase


class CommandLineArgumentParser(RequestParserBase):
    def __init__(self, loc):
        super().__init__()

        self.__loc = loc
        self.__logger = get_logger("cmd_args")

    @staticmethod
    def check_size_of_data(request_field, cmd_data):
        size_of_data = sys.getsizeof(cmd_data)
        if size_of_data > 35000000:
            raise werkzeug.exceptions.BadRequest(
                "The getting '{}' parameter size is too big. "
                "The current data size is {} bytes. "
                "35000000 bytes allows".format(request_field, size_of_data)
            )

    def validate(self, request):
        if not isinstance(request[self.__loc], dict):
            raise werkzeug.exceptions.BadRequest("Command line argument input is not a dictionary")

        self.check_size_of_data(self.__loc, request)

        for key, value in request[self.__loc].items():
            if not isinstance(key, str) or not isinstance(value, str):
                raise werkzeug.exceptions.BadRequest(
                    "Command line argument input has invalid key or value"
                )

    def parse(self, request):
        return_data = {}

        if not request or self.__loc not in request.keys():
            return return_data

        self.check_size_of_data(self.__loc, request)

        request_data = request[self.__loc]

        if isinstance(request_data, str):
            request_data = ast.literal_eval(request_data)

        return request_data
