-- --------------------------------------------------------------------------------
-- _120_template Group Routines
-- --------------------------------------------------------------------------------
DELIMITER $$$


create function template_Create(
    type_id_ int unsigned, 
    type_code_ varchar(30) binary,
    node_id_ int unsigned
) returns int unsigned
comment 'template takes ownership on node_id_'
not deterministic modifies sql data
begin
    declare type_id int unsigned default coalesce(type_id_, nodeType_GetByCode(type_code_));
    
    -- FORWARD: nodeLink_ResetLinks2 is defined in _95_extraUtils
    insert templateT(srcNodeTypeId, dstNodeId, dstNodeTypeId)
    select type_id, nodeLink_ResetLinks2(null, null, node_id_, false), n.nodeTypeId
    from nodeT n
    where n.id = node_id_;
    
    return type_id;
end$$$


create function template_Delete(
    type_id_ int unsigned, 
    type_code_ varchar(30) binary,
    node_id_ int unsigned
) returns int unsigned
not deterministic modifies sql data
begin
    declare type_id int unsigned default coalesce(type_id_, nodeType_GetByCode(type_code_));
    
    set @1 = nodeLink_UpdateStart();
    
    insert zzzDevNullTemplateT(n)
    select __node_Delete(t.dstNodeId)
    from templateT t
    where t.srcNodeTypeId = type_id
        and t.dstNodeId = coalesce(node_id_, t.dstNodeId);
    
    set @2 = nodeLink_UpdateEnd();

    -- deleted nodes will delete templateT record because of FK constraints
    /*delete from templateT
    where srcNodeTypeId = type_id
        and dstNodeId = coalesce(node_id_, dstNodeId);*/
    
    return 1;
end$$$


create function __template_DuplicateNode(node_id_ int unsigned) returns int unsigned
not deterministic modifies sql data
begin
    declare res int unsigned;
    declare internal_type_id varchar(10) binary;
    
    select nt.internalTypeId 
    into internal_type_id
    from nodeT n 
    join nodeTypeT nt on n.nodeTypeId = nt.id 
    where n.id = node_id_;
    
    case internal_type_id
        when 'tag' then
            set res = __tag_Duplicate(node_id_);
        when 'attribute' then
            set res = __attribute_Duplicate(node_id_);
        else
            call raiseError1('template', 'duplicate', internal_type_id, 'cannot duplicate node of this type');
    end case;
    
    return res;
end$$$


create function template_CreateSubs(node_id_ int unsigned) returns int unsigned
not deterministic modifies sql data
begin
    declare type_id int unsigned default (select n.nodeTypeId from nodeT n where n.id = node_id_);

    set @1 = nodeLink_UpdateStart();
    
    insert zzzDevNullTemplateT(n)
    select nodeLink_Relink(null, node_id_, __template_DuplicateNode(t.dstNodeId))
    from templateT t
    where t.srcNodeTypeId = type_id;

    set @2 = nodeLink_UpdateEnd();

    return node_id_;
end$$$

