# -*- coding: utf-8 -*-
"""
Created on Sun Mar 15 17:34:08 2020

@author: Sophie
"""

import ctypes
import weakref

from neticapy import enums
from neticapy import environ as envrn
from neticapy import neticaerror as err
from neticapy.loaddll import Netica

errdict_initialization = True

if errdict_initialization:    
    err_dict = {}  

class RawNeticaError:     

    def __init__(self, number, severity, mesg):
        """Create a new RawNeticaError 
        
        number refers to the error number and must be between 1 and 999, inclusive
        Like Netica-C NewError_ns
        """
        self.cptr = None # Initialize cptr for case where Netica raises an error during construction

        if isinstance(number, tuple):
            indicator, passed_cptr = number
            if indicator == 'from_environ_get_error':
                self.cptr = passed_cptr
            else:
                pass # raise some error
        else:
            Netica.NewError_ns.restype = ctypes.c_void_p
            cptr = Netica.NewError_ns(ctypes.c_void_p(self.cptr), ctypes.c_int(number),
                                    ctypes.c_int(enums.set_error_severity(severity)), ctypes.c_char_p(mesg.encode()))
            self.cptr = cptr
            
            if errdict_initialization:
                err_dict[cptr] = weakref.ref(self)
                                    
    def __del__(self):
        """Remove this Streamer, freeing all resources it consumes, including memory.
            
        Like Netica-C DeleteStream_ns.
        """
        if envrn.env is not None:
            Netica.DeleteStream_ns.restype = None
            Netica.DeleteStream_ns(ctypes.c_void_p(self.cptr))
            err.checkerr()
        if envrn.dict_initialization:
            del envrn.cptr_dict[self.cptr]
        self.cptr = None

    @property
    def number(self):
        """
        """
        Netica.ErrorNumber_ns.restype = ctypes.c_int
        err_num = Netica.ErrorNumber_ns(ctypes.c_void_p(self.cptr))
        return err_num

    @property
    def message(self):
        """
        """
        Netica.ErrorMessage_ns.restype = ctypes.c_char_p
        err_mesg = Netica.ErrorMessage_ns(ctypes.c_void_p(self.cptr))
        return err_mesg.decode()

    @property
    def severity(self):
        """
        """
        Netica.ErrorSeverity_ns.restype = ctypes.c_int
        err_sever = Netica.ErrorSeverity_ns(ctypes.c_void_p(self.cptr))
        return enums.get_error_severity(err_sever)

    def is_catagory(self, cond):
        """
        """
        Netica.ErrorCategory_ns.restype = ctypes.c_bool
        catagory = Netica.ErrorCategory_ns(ctypes.c_int(enums.set_error_condition(cond)), self.cptr)
        return bool(catagory)

    def clear(self):
        """
        """
        Netica.ClearError.restype = None
        Netica.ClearError(self.cptr)
        if errdict_initialization:
            del err_dict[self.cptr]
