'''
Created on 01.05.2017

@author: Mr. Jones
'''

from slimit.visitors.scopevisitor import Visitor

class DeleteVisitor(Visitor):
    
    def __init__(self,removals):
        self.removals = removals
        self.optimization = 0
        
    def set_removals(self,removals):
        self.removals = removals
    
    def visit(self, node):
        method = 'visit_%s' % node.__class__.__name__
        return getattr(self, method, self.generic_visit)(node)
    
    def visit_ExprStatement(self,node):
        if node.expr in self.removals:
            self.removals.append(node)

    def generic_visit(self, node):
        removal = []
        if node is None:
            return
        if isinstance(node, list):
            for child in node:
                if child in self.removals:
                    removal.append(child)
                else:
                    self.visit(child)
            temp = len(node.children())
            for i in removal:
                node.children().remove(i)
            if len(node.children()) < temp:
                self.optimization = 1
        else:
            for child in node.children():
                if child in self.removals:
                    removal.append(child)
                else:
                    self.visit(child)
            temp = len(node.children())
            for i in removal:
                node.children().remove(i)
            if len(node.children()) < temp:
                self.optimization = 1