import copy
import numpy as np
from neuron import h


class ResultsPAPModel:
    # class to copy data of simulations
    # necessary for MPI copy as NEURON components cannot be copied

    dont_copy = [
        "PAP",
        "PAPs",
        "soma",
        "branches",
        "branch",
        "NMDAs",
        "GluTs",
        "GABAas",
        "NCs",
        "GENEobj",
        "equiDistSec",
        "shell_synapse_glut",
        "record_multiPAPs",
    ]
    memcurrents = [
        "iKPAP",
        "iClPAP",
        "iNaPAP",
        "iMemPAP",
        "iKSoma",
        "iClSoma",
        "iNaSoma",
        "iMemSoma",
        "iNCXPAP",
        "somaMemCurr",
        # "iNMDA"
    ]
    ppcurrents = ["iGluT", "iNMDA", "iGluTSoma", "iGABA", "VClampI"]

    def copyAttr(self):
        """Deep-copy this instance's attributes (excluding NEURON-only objects) into a new ResultsPAPModel, converting membrane currents to nA using compartment area, summing point-process currents when not recording single synapses, and rescaling currents from nA to pA."""
        # print("copying to result class")
        newInstance = ResultsPAPModel()
        # print(self.__dict__)
        newInstance.__dict__ = {
            attr: copy.deepcopy(self.__dict__[attr])
            for attr in self.__dict__
            if attr not in self.dont_copy
        }
        # total current calculate mA/cm2 to nA
        for attr in newInstance.__dict__:
            if attr in self.memcurrents:
                if "PAP" in attr:
                    area = self.PAParea
                else:
                    area = self.somaArea
                newInstance.__dict__[attr] = (
                    np.array(newInstance.__dict__[attr]) * area * 1e-8
                )

        # sum all ppcurrents
        if not self.record_single_synapse:
            for attr in newInstance.__dict__:
                if attr in self.ppcurrents and type(newInstance.__dict__[attr]) is list:
                    for i, vec in enumerate(newInstance.__dict__[attr]):
                        if i == 0:
                            tmp = np.array(vec)
                        else:
                            tmp += np.array(vec)
                    newInstance.__dict__[attr] = tmp
        # nA to pA
        currList = self.memcurrents + self.ppcurrents
        for attr in newInstance.__dict__:
            if attr in currList:
                newInstance.__dict__[attr] = np.array(newInstance.__dict__[attr]) * 1e3

        # Convert Vector to list
        # for attr in newInstance.__dict__:
        #     if isinstance(newInstance.__dict__[attr],h.Vector):
        #         newInstance.__dict__[attr] = list(newInstance.__dict__[attr])
        return newInstance

    def cleanNEURONVariables(self):
        """Null out every HocObject reference held in the NEURON h namespace to release memory."""
        all_hoc_names = dir(h)

        for name in all_hoc_names:
            try:
                obj = getattr(h, name)

                if "hoc.HocObject" in str(type(obj)) and not callable(obj):
                    setattr(h, name, None)
                    print(f"Nullified objref: {name}")
            except (AttributeError, TypeError):
                continue

    def getRMP(self):
        """Return the resting membrane potential as the last recorded somatic voltage value."""
        RMP = list(self.vSoma)[-1]
        return RMP