# vim: tabstop=4 shiftwidth=4 softtabstop=4
# -*- coding: utf-8 -*-
#

import sys
import os
import re
from ftg.utils.common import CommonUtils
from ftg.flow_table import FlowTable
from ftg.flow_priority import FlowPriority
from ftg.flow_entry import FlowEntry
from ftg.parser.base import BaseParser


class CSVParser(BaseParser):

    def parse(self):
        self.util.debug_out(self.dump_file)
        for dump_line in open(self.dump_file, 'r'):
            dump_line = dump_line.rstrip()
            instructions = []
            if self.util.d_push(re.match(r'\"(\d+)-(\d+)\",\"(.*)\",\"(.*)\"', dump_line)) is not None:
                match = self.util.d_pop()
                table_no = match.group(1)
                priority_no = match.group(2)
                match_exp = match.group(3)
                instruction = match.group(4)
                instructions = self._parse_actions_with_bracket(
                    instruction, instructions)
                self.util.debug_out(
                    "[1] " + table_no + "-" + priority_no + " m:" + match_exp + " a:" + instruction)
                self.regist_flow(
                    table_no, priority_no, match_exp, instructions)
            elif self.util.d_push(re.match(r'\"(\d+)\",\"(.*)\",\"(.*)\"', dump_line)) is not None:
                match = self.util.d_pop()
                table_no = match.group(1)
                priority_no = "32768"
                match_exp = match.group(2)
                instruction = match.group(3)
                instructions = self._parse_actions_with_bracket(
                    instruction, instructions)
                self.util.debug_out(
                    "[3] " + table_no + "-" + priority_no + " m:" + match_exp + " a:" + instruction)
                self.regist_flow(
                    table_no, priority_no, match_exp, instructions)
            elif dump_line.strip() == "":
                continue
            elif self.util.d_push(re.match(r'\"Table-Priority\",\"Match\",\"Instruction\"', dump_line)) is not None:
                continue
            else:
                if not self.util.d_push(re.match(r'.*NXST_FLOW reply.*', dump_line)):
                    self.util.error_out("PARSE ERROR: " + dump_line)

