from abaqus import *
from abaqusConstants import *


def create_load(data, **kwargs):
    """
    Create and apply compressing load at each connection between connectors and ipMTs

    :param data: list containing all ipMTs and connectors of the model

    :type data: list

    :param kwargs: model parameters

    :type kwargs: dict

    :return: Null

    :rtype: Null
    """
    # Call the current assembly
    modelname = kwargs['modelname']
    a = mdb.models[modelname].rootAssembly
    StepName = kwargs['StepName']
    LoadVal = kwargs['CompressiveLoad']
    # Select vertices to apply load
    # Iterate through unique ipMT names
    mt_names = [sublist[0] for sublist in data]
    mt_names = set(mt_names)
    # Specify that the load is negative for all ipMTs that have even numbers and positive otherwise
    for mtname in mt_names:
        if int(mtname[-1]) % 2 == 0:
            load = -LoadVal
        else:
            load = LoadVal
        # Locate the points to which loads are to be applied
        for sublist in data:
            if mtname == sublist[0]:
                connector_end = sublist[3]
                connector_name = sublist[1]

                # Select points that connect ipMTs with connectors
                ConnectorEnd = a.instances[connector_name].vertices[connector_end].pointOn
                loadPoint = a.instances[connector_name].vertices.findAt(ConnectorEnd, )
                loadName = 'Load-' + connector_name + '-' + str(connector_end)
                loadRegion = a.Set(vertices=loadPoint,
                                     name=loadName)
                # Apply loads
                mdb.models[modelname].ConcentratedForce(name=loadName,
                                                        createStepName=StepName,
                                                        region=loadRegion,
                                                        cf3=load,
                                                        distributionType=UNIFORM,
                                                        field='',
                                                        localCsys=None)


def create_bc(**kwargs):
    """
    Fix growing ends of aMTs where they are attached to the membrane

    :param kwargs: model parameters

    :type kwargs: dict

    :return: Null

    :rtype: Null
    """
    modelname = kwargs['modelname']
    # Call for the current assembly
    a = mdb.models[modelname].rootAssembly
    aMTnames = kwargs['aMTnames']
    for i in range(len(aMTnames)):
        v = a.instances[aMTnames[i]].vertices
        verts = v.getSequenceFromMask(mask=('[#2]', ), )
        region = a.Set(vertices=verts, name='FixedBCregion_'+str(i))
        mdb.models[modelname].EncastreBC(name='FixedBC_'+str(i),
                                         createStepName='Initial',
                                         region=region,
                                         localCsys=None)
