import json

from streamduo.models.record import Record

class PublicRecordController:
    """
    This class manages the reading and writing of records to streams.
    """

    def __init__(self, client):
        self.client = client

    def write_record(self, stream_id, json_payload, record_id=None):
        """
        Writes a single record to the stream.
        :param stream_id: (String) Stream ID to write to
        :param json_payload: (Dict OR JSON formatted String) The payload of the record
        :param record_id: (String) OPTIONAL - Used in the case you want to force a particular record ID.
        If left null, record ID will be generated by API
        :return: (Requests Response) API response, body will be a Record object Dict.
        """
        record = Record()
        record.recordId = record_id
        if isinstance(json_payload, str):
            record.dataPayload = json.loads(json_payload)
        else:
            record.dataPayload = json_payload
        return self.client.call_api("POST",
                                    f"/stream/{stream_id}/record",
                                    body=record.to_json()
                                    )


