<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
 def assign_type_to_resource(type_id, resource_type, resource_id,**kwargs):
 """Assign new type to a resource. This function checks if the necessary attributes are present and adds them if needed. Non existing attributes are also added when the type is already assigned. This means that this function can also be used to update resources, when a resource type has changed. """


    if resource_type == 'NETWORK':
        resource = db.DBSession.query(Network).filter(Network.id==resource_id).one()
    elif resource_type == 'NODE':
        resource = db.DBSession.query(Node).filter(Node.id==resource_id).one()
    elif resource_type == 'LINK':
        resource = db.DBSession.query(Link).filter(Link.id==resource_id).one()
    elif resource_type == 'GROUP':
        resource = db.DBSession.query(ResourceGroup).filter(ResourceGroup.id==resource_id).one()

    res_attrs, res_type, res_scenarios = set_resource_type(resource, type_id, **kwargs)

    type_i = db.DBSession.query(TemplateType).filter(TemplateType.id==type_id).one()
    if resource_type != type_i.resource_type:
        raise HydraError("Cannot assign a %s type to a %s"%
                         (type_i.resource_type,resource_type))

    if res_type is not None:
        db.DBSession.bulk_insert_mappings(ResourceType, [res_type])

    if len(res_attrs) > 0:
        db.DBSession.bulk_insert_mappings(ResourceAttr, res_attrs)

    if len(res_scenarios) > 0:
        db.DBSession.bulk_insert_mappings(ResourceScenario, res_scenarios)

    #Make DBsession 'dirty' to pick up the inserts by doing a fake delete.
    db.DBSession.query(Attr).filter(Attr.id==None).delete()

    db.DBSession.flush()

    return db.DBSession.query(TemplateType).filter(TemplateType.id==type_id).one()