from __future__ import annotations

from typing import Type

from ._cdata import CData
from ._ffi import ffi, lib
from ._profile import Profile

__all__ = ["Output"]


class Output:
    def __init__(self, nmm_output: CData):
        self._nmm_output = nmm_output
        if self._nmm_output == ffi.NULL:
            raise RuntimeError("`nmm_output` is NULL.")

    @classmethod
    def create(cls: Type[Output], filepath: bytes) -> Output:
        return cls(lib.nmm_output_create(filepath))

    def write(self, prof: Profile):
        err: int = lib.nmm_output_write(self._nmm_output, prof.nmm_profile)
        if err != 0:
            raise RuntimeError("Could not write profile.")

    def close(self):
        err: int = lib.nmm_output_close(self._nmm_output)
        if err != 0:
            raise RuntimeError("Could not close output.")

    def __del__(self):
        if self._nmm_output != ffi.NULL:
            self.close()
            lib.nmm_output_destroy(self._nmm_output)

    def __enter__(self):
        return self

    def __exit__(self, exception_type, exception_value, traceback):
        del exception_type
        del exception_value
        del traceback
        self.close()
