# coding: utf-8

from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals

import library.python.resource as ya_resource

from collections import namedtuple
from enum import Enum, unique
from lark import Lark, Transformer, v_args


@unique
class Operator(Enum):
    """
    Operators enum
    """
    equals = '='
    not_equals = '!='
    in_ = 'IN'
    not_in = 'NOT IN'


Filter = namedtuple('Filter', ['attribute', 'operator', 'value'])


class TreeToFilterList(Transformer):
    @v_args(inline=True)
    def filter(self, attribute_path_tree, operator_and_value_tree):
        """
        Make filter
        """
        attribute_path = attribute_path_tree.children[0][1:-1]
        operator, value = operator_and_value_tree.children
        return Filter(str(attribute_path), operator=Operator[operator.data], value=str(value))

    @v_args(inline=True)
    def filters_list(self, *rule_list):
        """
        Make filter list
        Remove anything except Filters from rules
        """
        return [r for r in rule_list if isinstance(r, Filter)]

    @v_args(inline=True)
    def string(self, s):
        return s[1:-1]


grammar = ya_resource.find('simplified_filter.lark').decode()

Parser = Lark(grammar, parser='lalr', start=['filters_list'], propagate_positions=True, transformer=TreeToFilterList())
