 Delimiter //
/**
 * If the function short label is provided, and is in application, set the function id with it
 * Else throw a warning and set the function id to the prefered one
 * 
 * @param int batchnum
 * @author Benoit
 * @ticket #2110
 */ 
 Drop Procedure if Exists LOADER_CONTACTS_NORMALIZE_MAP_FUNCTION_PROVIDED//
 
Create Procedure LOADER_CONTACTS_NORMALIZE_MAP_FUNCTION_PROVIDED (
    In batchnum int
 )
 Begin
 
    Set @idAdminParams = GET_LOADER_INFO('ID_ADMIN_PARAMS', batchnum);

    Set @idFunctionPrefered = (Select ID_DF_FUNCTIONS 
                               From DF_FUNCTIONS F
                               Where F.ADMIN_PARAMS_ID_ADMIN_PARAMS = @idAdminParams 
                                     And F.DF_FUNCTIONS_PREFERENCE = 1
                               Limit 1); -- Ne pas faire confiance aux données sans contraintes...

    UPDATE
        LOADER_CONTACTS C
        INNER JOIN LOADER_STATUS S
            ON S.ID_LOADER_STATUS = C.LOADER_STATUS_ID_LOADER_STATUS
        LEFT JOIN DF_FUNCTIONS F
            ON F.ADMIN_PARAMS_ID_ADMIN_PARAMS = @idAdminParams
            AND F.DF_FUNCTIONS_SHORT_LABEL = C.DF_FUNCTIONS_SHORT_LABEL
    SET
        C.DF_FUNCTIONS_ID_DF_FUNCTIONS = 
            (CASE WHEN F.ID_DF_FUNCTIONS IS NOT NULL
                THEN F.ID_DF_FUNCTIONS
                ELSE @idFunctionPrefered
            END)
        , S.LOADER_STATUS_WARNCOUNT = 
            (CASE WHEN F.ID_DF_FUNCTIONS IS NULL
                THEN S.LOADER_STATUS_WARNCOUNT + 1
                ELSE S.LOADER_STATUS_WARNCOUNT
            END)
        , S.LOADER_STATUS_WARNMSGS = 
            (CASE WHEN F.ID_DF_FUNCTIONS IS NULL
                THEN LOADER_CONCAT_ERR(S.LOADER_STATUS_WARNMSGS, Concat('Fonction abrégée à créer : ', C.DF_FUNCTIONS_SHORT_LABEL) )
                ELSE S.LOADER_STATUS_WARNMSGS
            END)
    WHERE 
        S.LOADER_STATUS_BATCH_NUM = batchnum
        AND C.DF_FUNCTIONS_ID_DF_FUNCTIONS IS NULL
        AND Coalesce(C.DF_FUNCTIONS_SHORT_LABEL, '') != ''
    ;
    
 End //
 Delimiter ;