-- --------------------------------------------------------------------------------
-- _050_allowedNodeLink Group Routines
-- --------------------------------------------------------------------------------
DELIMITER $$$

create function __allowedNodeLink_CanLinkFrom(node_type_id_ int unsigned) returns int unsigned
deterministic
begin
    if (select canLinkFrom from nodeTypeT where id = node_type_id_) != 'y' then
        call raiseError1('allowedNodeLink', 'linkFrom', node_type_id_, 'cannot create allowed link from the node type');
    end if;
    
    return 1;
end$$$


create function __allowedNodeLink_CanLinkTo(node_type_id_ int unsigned) returns int unsigned
deterministic
begin
    if (select canLinkTo from nodeTypeT where id = node_type_id_) != 'y' then
        call raiseError1('allowedNodeLink', 'linkTo', node_type_id_, 'cannot create allowed link to the node type');
    end if;
    
    return 1;
end$$$


create function allowedNodeLink_Create(
    src_node_type_id_ int unsigned,
    dst_node_type_id_ int unsigned,
    essential_ enum('n', 'y'),
    single_src_ enum('n', 'y')
) returns int unsigned
not deterministic modifies sql data
begin
    set @1 = __allowedNodeLink_CanLinkFrom(src_node_type_id_) and __allowedNodeLink_CanLinkTo(dst_node_type_id_);
    
    insert allowedNodeLinkT (
        srcNodeTypeId,
        dstNodeTypeId,
        essential,
        singleSrc) 
    values (
        src_node_type_id_,
        dst_node_type_id_,
        essential_,
        single_src_) 
    on duplicate key update 
        allowedNodeLinkT.essential = essential_,
        allowedNodeLinkT.singleSrc = single_src_;
    
    return 1;
end$$$


create function allowedNodeLink_Delete(
    src_node_type_id_ int unsigned,
    dst_node_type_id_ int unsigned
) returns int unsigned
not deterministic modifies sql data
begin
    set @1 = __allowedNodeLink_CanLinkFrom(src_node_type_id_) and __allowedNodeLink_CanLinkTo(dst_node_type_id_);

    delete from allowedNodeLinkT 
    where srcNodeTypeId = src_node_type_id_
        and dstNodeTypeId = dst_node_type_id_;
        
    return 1;
end$$$


create function allowedNodeLink_Update(
    src_node_type_id_ int unsigned,
    dst_node_type_id_ int unsigned,
    essential_ enum('n', 'y'),
    single_src_ enum('n', 'y')
) returns int unsigned
begin
    update allowedNodeLinkT set
        essential = coalesce(essential_, essential),
        singleSrc = coalesce(single_src_, singleSrc),
        changed = current_timestamp()
    where srcNodeTypeId = src_node_type_id_
        and dstNodeTypeId = dst_node_type_id_;
    
    return 1;
end$$$


