from struct import unpack

from nmreval.io.nmrreader import NMRReader

from ..Qt import QtCore


class QNMRReader(QtCore.QObject):
    data_read = QtCore.pyqtSignal(list)
    file_ext = ['.nmr']

    def __init__(self):
        super().__init__()
        self._reader = NMRReader()

    def __call__(self, fname):
        with fname.open('rb') as fp:
            s16 = fp.read(16)

            # copied from whichdb (Python 2.7) to look for magic value of dbhash
            (magic,) = unpack("=l", s16[-4:])
            if magic in (0x00061561, 0x61150600):
                self._reader(fname, '-1')

            else:
                (magic,) = unpack('<16s', s16)
                if magic.startswith(b'NMREVAL'):
                    self._reader(fname, str(magic[7:].rstrip(b'\x00'), 'utf8'))

        return self

    def exec(self):
        data = self._reader.make_data()
        self.data_read.emit([data])
