#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 
# Copyright 2019 Jay Arrowfield.
# 
# This is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3, or (at your option)
# any later version.
# 
# This software is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this software; see the file COPYING.  If not, write to
# the Free Software Foundation, Inc., 51 Franklin Street,
# Boston, MA 02110-1301, USA.
# 

import numpy
import pmt
from gnuradio import gr

class message_filter(gr.basic_block):
    """
    docstring for block message_filter
    """
    def __init__(self, filter='freq'):
        gr.basic_block.__init__(self,
            name="message_filter",
            in_sig=None,
            out_sig=None)

        self.filter = filter

        # Register in / out message ports
        self.port_in = pmt.intern("in")
        self.port_out = pmt.intern("out")

        self.message_port_register_in(self.port_in)
        self.message_port_register_out(self.port_out)

        # Register in message handler
        self.set_msg_handler(self.port_in, self.msg_handler)

    def delegate_pair(self, pair):
        key = pmt.car(pair)
        key_str = pmt.symbol_to_string(key)

        if self.filter in key_str:
            self.message_port_pub(self.port_out, pair)

    def msg_handler(self, msg):
        # Üble Verrenkungen, um fest zu stellen of dict oder pair
        if pmt.is_dict(msg):
            items = pmt.dict_items(msg)
            try:
                # Dict, wenn len_items > 1
                len_items = pmt.length(items)

                # Iterate through dict to get single pairs
                for n in range(0, len_items):
                    pair = pmt.nth(n, items)
                    self.delegate_pair(pair)
            except:
                # Wrong Type exception -> pair
                self.delegate_pair(msg)


    def forecast(self, noutput_items, ninput_items_required):
        #setup size of input_items[i] for work call
        for i in range(len(ninput_items_required)):
            ninput_items_required[i] = noutput_items

    def general_work(self, input_items, output_items):
        output_items[0][:] = input_items[0]
        consume(0, len(input_items[0]))
        #self.consume_each(len(input_items[0]))
        return len(output_items[0])
