import sys
import struct

from plesk_mail_migrator.core.dumps.dump_reader import DumpReader
from plesk_mail_migrator.core.entities.mail_message import MailMessage
from plesk_mail_migrator.core.entities.utils.imap_flags_utils import IMAPFlagsUtils


class StreamDumpReader(DumpReader):
    def __init__(self, stream=None):
        if stream is None:
            self._stream = sys.stdin
        else:
            self._stream = stream

    def read_message(self):
        uid = self._read_string()
        if uid is None:
            return None
        folder = self._read_string()
        flags = IMAPFlagsUtils.flags_from_number(self._read_int())
        body = self._read_string()
        return MailMessage(uid, folder, flags, body)

    def _read_int(self):
        data = self._stream.read(4)
        if len(data) == 4:
            return struct.unpack("=i", data)[0]
        else:
            return None

    def _read_string(self):
        length = self._read_int()
        if length is None:
            return None
        return self._stream.read(length)
