from threading import Lock
import inspect
import csv

from pyretic.examples.shared import *
from pyretic.lib.corelib import *
from pyretic.lib.std import *
from pyretic.lib.query import *
from pyretic.core.runtime import virtual_field

resourcesFile = "pyretic/examples/configs/resources.csv"
resourceRulesFile = "pyretic/examples/configs/firewall-groups.csv"

class firewall_groups(DynamicPolicy):
    def __init__(self):
        self.debug = 0
        self.rules = {}
        self.loadRules()
        super(firewall_groups,self).__init__(true)
        self.update_policy()

    def loadRulesGroup(self, headers, row):
        self.rules[row[0]] = {}
        
        for i in range(1, len(row)):
            self.rules[row[0]][headers[i]] = False if row[i] == "" else True
    
    def loadRules(self):
        with open(resourceRulesFile, 'rb') as f:
            reader = csv.reader(f, delimiter=';')
            line = 0
            for row in reader:
                line = line + 1
                if line == 1:
                    headers = row
                    continue
                
                self.loadRulesGroup(headers, row)
    
    def update_policy (self):
        self.policy = identity
        
        for port in portsList:
            for device in port["devices"]:
                for srcGroup in self.rules:
                    
                    try:
                        result = self.rules[srcGroup][device["group"]]
                    except KeyError:
                        result = False
                    
                    if result == False:
                        if self.debug:
                            print "DROP", port["switch"], port["port"], srcGroup, device["group"]
                        self.policy = if_(match(switch=int(port["switch"]),outport=int(port["port"]),group=srcGroup), drop, self.policy)
        
        if self.debug:
            print "firewall_groups POLICY", self.policy
                    
def main():
    return firewall_groups()

