""" Helper socket classes designed for testing SLIS """
# Copyright (C) 2013 Libor Polčák
#
# This program 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 of the License, or
# (at your option) any later version.
#
# This program 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 program.  If not, see <http://www.gnu.org/licenses/>.

from ..tools.numeric import inttoNbytes

import os
import tempfile

class HelperUnderlyingSocket():

    def __init__(self, buf = b"", probeid = 1, peer = None):
        self.peer = peer
        self.probeid = probeid
        self.print_stats = False
        header = b"\x01\x00" + inttoNbytes(self.probeid, 4)
        self.fakeSock = tempfile.TemporaryFile("w+b")
        self.fakeSock.write(header + buf)
        self.fakeSock.seek(0)

    def close(self):
        self.fakeSock.close()

    def closed(self):
        return self.fakeSock.closed

    def fileno(self):
        return self.fakeSock.fileno()

    def getpeername(self):
        return self.peer

    def recv(self, count):
        return self.fakeSock.read(count)

    # Test specific interface
    def buffer_one_packet(self, blob, interface, ts_unix, ts_ns, rid0, rid1):
        # Set position to end of file
        current_pos = self.fakeSock.tell()
        os.lseek(self.fakeSock.fileno(), 0, os.SEEK_END)
        # Insert blob
        blob_size = len(blob)
        hdr = MakeBlobHeader(blob_size, interface, ts_unix, ts_ns, rid0, rid1)
        self.fakeSock.write(hdr + blob)
        expected = {"Blob Size": blob_size,
                #"Interface": interface,
                "Timestamp (sec)": ts_unix,
                "Timestamp (ns)": ts_ns // 1000,
                "RID": [rid0, rid1] if rid0 != rid1 else [rid0],
                "Blob": blob,
                }
        # Return position
        self.fakeSock.seek(current_pos)
        return expected

def MakeBlobHeader(blob_size, interface, ts_unix, ts_ns, rid0, rid1):
    return inttoNbytes(blob_size, 2) + \
            inttoNbytes(interface, 1) + \
            b"\x00" + \
            inttoNbytes(ts_unix, 4) + \
            inttoNbytes(ts_ns, 4) + \
            inttoNbytes(rid0, 2) + \
            inttoNbytes(rid1, 2)
