# -*- coding: utf-8 -*-
#
# michael a.g. aïvázis <michael.aivazis@para-sim.com>
# (c) 1998-2022 all rights reserved


# externals
import csv
# superclass
from journal.Device import Device
# my renderer
from .Renderer import Renderer


# write message to a stream
class Device(Device):
    """
    Journal device that writes messages to a csv file
    """


    # interface
    def alert(self, entry):
        """
        Generate an alert.

        Alerts are user-facing; they are generated by {info}, {warning}, and {error}
        """
        # generate the csv record and inject it in the file
        return self.inject(entry)


    def memo(self, entry):
        """
        Issue a memo

        Memos are developer-facing; they are generated by {debug} and {firewall}
        """
        # generate the csv record and inject it in the file
        return self.inject(entry)


    # metamethods
    def __init__(self, stream, name="csv", **kwds):
        # chain up
        super().__init__(name=name, **kwds)
        # instantiate my renderer
        self.renderer = Renderer()
        # make a {csv} writer out of the stream
        self.writer = csv.writer(stream, quoting=csv.QUOTE_ALL)
        # all done
        return


    # implementation details
    def inject(self, entry):
        """
        Record a message
        """
        # get the record from my renderer
        record = self.renderer.render(entry)
        # and write it out
        self.writer.writerow(record)
        # all done
        return self


# end of file
