"""
Embedded Python Blocks:

Each time this file is saved, GRC will instantiate the first class it finds
to get ports and parameters of your block. The arguments to __init__  will
be the parameters. All of them are required to have default values!
"""

import numpy as np
from gnuradio import gr
import os
import time
import matplotlib.pyplot as plt
import sys
import gc

class Simsi_Sink(gr.sync_block):  # other base classes are basic_block, decim_block, interp_block
    """Embedded Python Block example - a simple multiply const"""

    def __init__(self, SaveDir="./signal", FileTag="fragment_", SplitSize=1000000, Delay=2):  # only default arguments here
        """arguments to this function show up as parameters in GRC"""
        gr.sync_block.__init__(
            self,
            name='Simsi_Sink',   # will show up in GRC
            in_sig=[np.complex64],
            out_sig=None#[np.complex64]
        )
        self.Delay = Delay
        self.FileTag = FileTag
        self.SplitSize = SplitSize
        
        self.SaveDir = SaveDir
        if not os.path.exists(self.SaveDir) and self.SaveDir == "./signal":
            os.mkdir("signal")
            
        self.it = 0
        self.Signal = np.array([], dtype=np.float32)
        self.data_dir = SaveDir

        self.last_file_path = self.data_dir + "/" + self.FileTag + str(self.it)
        self.last_fd = open(self.last_file_path, "wb")
        self.last_file_len = 0


        self.reading_in_progress_file_path = self.data_dir + "/reading_in_progress"
        self.reading_in_progress_file_fd = open(self.reading_in_progress_file_path, "wb")

        print(self.Signal)
        print(self.data_dir)
        # if an attribute with the same name as a parameter is found,
        # a callback is registered (properties work, too).

    def work(self, input_items, output_items):
        """example: multiply with constant"""
        length = len(input_items[0])
        self.last_file_len += length

        if self.last_file_len > self.SplitSize:
            print("Saving file: " + str(self.last_file_path))
            length = length - (self.last_file_len - self.SplitSize)
            self.last_fd.write(input_items[0][0:length].copy())
            self.it += 1
            self.last_file_len = 0
            self.last_file_path = self.data_dir + '/' + self.FileTag + str(self.it)
            self.last_fd.close()
            self.reading_in_progress_file_fd.close()
            os.remove(self.reading_in_progress_file_path)
            time.sleep(self.Delay)
            self.reading_in_progress_file_fd = open(self.reading_in_progress_file_path, "wb")
            self.last_fd = open(self.last_file_path, "wb")
            
        else:
            self.last_fd.write(input_items[0].copy())


        return len(input_items[0])
