import abc
import csv
from datetime import datetime

from pikos.abstract_monitors import PikosError


class RecorderError(PikosError): pass


def _make_filename():
    time = datetime.now()
    return '{0}.profile'.format(time.strftime('%Y-%m-%d_%H-%M-S'))


class AbstractRecorder(object):

    __metaclass__ = abc.ABCMeta

    @abc.abstractmethod
    def prepare(self):
        ''' Perform any setup required before the recorder is used
        '''

    @abc.abstractmethod
    def finalize(self):
        ''' Perform any tasks to finalize and clean up when the
        recording is completed
        '''

    @abc.abstractmethod
    def record(self, *args, **kwargs):
        ''' Record a measurement. '''


class CSVRecorder(AbstractRecorder):

    def __init__(self, filename=None):
        self._filename = _make_filename() if (filename is None) else filename
        self._csvfile = open(self._filename, 'wb', buffering=0)
        self._writer = csv.writer(self._csvfile)
        self._started = False

    def prepare(self, fields):
        if not self._started:
            self._writer.writerow(fields)
            self._started = True

    def finalize(self):
        pass

    def record(self, values):
        self._writer.writerow(values)

class ConsoleRecorder(AbstractRecorder):

    def __init__(self):
        pass

    def prepare(self, fields):
        print "RECORDING STARTS"

    def finalize(self):
        print "RECORDING FINISHED"

    def record(self, values):
        print values

@@ -703,17 +703,16 @@
 t. '''%0A%0A
-%0A
 class CS
@@ -777,16 +777,36 @@
 ame=None
+, record_filter=None
 ):%0A     
@@ -1020,16 +1020,137 @@
  = False
+%0A        if record_filter is None:%0A            record_filter = lambda x: True%0A        self._record_filter = record_filter
 %0A%0A    de
@@ -1340,32 +1340,76 @@
 (self, values):%0A
+        if self._record_filter(values):%0A    
         self._wr
@@ -1490,39 +1490,168 @@
 _init__(self
-):%0A        pass
+, record_filter=None):%0A        if record_filter is None:%0A            record_filter = lambda x: True%0A        self._record_filter = recorde_filter
 %0A%0A    def pr
@@ -1816,8 +1816,9 @@
  values%0A
+%0A

allow record filtering