from dataclasses import dataclass

import werkzeug.exceptions

from task.parsers.base import RequestParserBase


@dataclass
class ObjectParameter:
    remote: str
    local: str
    preserve: bool = False


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

        self.__loc = loc

    def validate(self, request):
        if not isinstance(request[self.__loc], list):
            raise werkzeug.exceptions.BadRequest("Objects input is not a list")

        for obj in request[self.__loc].items():
            if not isinstance(obj, dict):
                raise werkzeug.exceptions.BadRequest("Objects input has invalid value")

            if "remote" not in obj.keys() or "local" not in obj.keys():
                raise werkzeug.exceptions.BadRequest("Object input has missing mandatory element")

            if not isinstance(obj["remote"], str) or not isinstance(obj["local"], str):
                raise werkzeug.exceptions.BadRequest("Object input has invalid mandatory element")

    def parse(self, request):
        try:
            request = request[self.__loc]
            if not request:
                return []
            return [
                ObjectParameter(
                    remote=request["remote"],
                    local=request["local"],
                    preserve=request["preserve"] if "preserve" in request.keys() else False,
                )
                for obj in request[self.__loc]
            ]
        except KeyError:
            pass
        return []
