/* $Id$ */
/*============================================================================*
 |                 Copyright (c) 2016 Applaud Solutions UK Ltd                |
 |                             All rights reserved                            |
 *===========================================================================*/

SET VERIFY OFF
SET FEEDBACK OFF
SET SCAN OFF
WHENEVER OSERROR  EXIT FAILURE ROLLBACK
WHENEVER SQLERROR EXIT FAILURE ROLLBACK

DECLARE

  --
  -- Local constants and variables
  --
  l_SERVICE CONSTANT xxas_com_service_repository.service_name%TYPE
                       := 'RandomAdverts';

BEGIN

  xxas_com_sr_pkg.set_rest_service
    (p_service_name       => l_SERVICE
    ,p_description        => 'Random Adverts'
    ,p_path               => '/random-adverts'
    ,p_consumes           => 'application/xml'
    ,p_produces           => 'application/xml');

  xxas_com_sr_pkg.set_rest_method
    (p_service_name       => l_SERVICE
    ,p_method_name        => 'Block'
    ,p_description        => 'Find existing blocks matching the given criteria'
    ,p_methods            => 'GET'
    ,p_path               => 'block'
    ,p_remove_root_ele    => true
    ,p_sql                =>
      q'[
        SELECT XMLElement
                 ("data"
                 ,XMLAttributes
                   ('true' as "json:force-array"
                   ,'http://json.org/' as "xmlns:json")
                 ,XMLAgg
                   (XMLElement
                     ("block"
                     ,XMLForest
                       (rslt.function_id   "id"
                       ,decode(rslt.prompt,null,'Untitled',rslt.prompt) || ' (' || rslt.function_name || ')' "value"
                       ,decode(rslt.prompt,null,'Untitled',rslt.prompt) || ' (' || rslt.function_name || ')' "label")
                     )
                   )
                 ) "data"
        FROM   xxas_block_advert_v rslt
        WHERE  UPPER(rslt.function_name) like UPPER('%' || {requestParam.q} || '%')
        AND    rslt.function_id NOT IN (SELECT fme.function_id 
                                        FROM   fnd_menus fm
                                              ,fnd_menu_entries_vl fme
                                        WHERE  fm.menu_name = {requestParam.excludeAdGrpBlock}
                                        AND    fm.menu_id = fme.menu_id)
        AND    rslt.function_id != {requestParam.functionId}
      ]'
    );

END;
/
COMMIT;
EXIT;
