-- --------------------------------------------------------------------------------
-- _950_extraUtils Group Routines
-- --------------------------------------------------------------------------------
DELIMITER $$$


create function nodeLink_ResetLinks(
    link_code_ varchar(30) binary, 
    root_type_code_ varchar(30) binary, 
    dst_id_ int unsigned,
    recreate_root_links_ int
) returns int unsigned
not deterministic modifies sql data
begin
    declare link_code varchar(30) binary;
    declare link_id int unsigned;
    declare recreate_root_links int default coalesce(recreate_root_links_, 1);
    
    select nlt.id, nlt.code into link_id, link_code
    from nodeLinkTypeT nlt join nodeLinkTypeT nltdef on nltdef.isDefault = 'y'
    where nlt.code = coalesce(link_code_, nltdef.code);

    drop temporary table if exists nodeLinkResetLinksDeletes;
    create temporary table nodeLinkResetLinksDeletes(
        srcNodeId int unsigned,
        primary key(srcNodeId)
    );
    
    insert nodeLinkResetLinksDeletes(srcNodeId)
    select nl.srcNodeId
    from nodeLinkT nl
    where nl.nodeLinkTypeId = link_id
        and nl.dstNodeId = dst_id_
        and nl.metric = 1;
/*        and exists(
                select 1 
                from nodeLinkT nl2 
                join nodeV n2 on nl2.srcNodeId = n2.id
                where nl2.nodeLinkTypeId = link_id
                    and nl2.dstNodeId = nl.srcNodeId
                    and nl2.metric > 0
                    and n2.is Root = 'y'
                    and n2.typeCode = coalesce(root_type_code_, n2.typeCode));*/
    
    set @1 = nodeLink_UpdateStart();
    
    insert zzzDevNullLinkT(n)
    select __nodeLink_Delete(link_code, nlrld.srcNodeId, dst_id_, null)
    from nodeLinkResetLinksDeletes nlrld;

    set @2 = recreate_root_links and __node_LinkDefaults(link_code, dst_id_);
    
    set @3 = nodeLink_UpdateEnd();

    drop temporary table nodeLinkResetLinksDeletes;
    
    return 1;
end$$$


create function nodeLink_ResetLinks2(
    link_code_ varchar(30) binary, 
    root_type_code_ varchar(30) binary, 
    dst_id_ int unsigned,
    recreate_root_links_ int
) returns int unsigned
comment 'calls nodeLink_ResetLinks and returns dst_id'
not deterministic modifies sql data
begin
    set @1 = nodeLink_ResetLinks(link_code_, root_type_code_, dst_id_, recreate_root_links_);
    return dst_id_;
end$$$

