/* $Id$ */
/*============================================================================*
 |                 Copyright (c) 2015 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
                       := 'Form';

BEGIN

  xxas_com_sr_pkg.set_rest_service
    (p_service_name       => l_SERVICE
    ,p_description        => 'User forms'
		,p_path               => '/forms/{functionId}'
    ,p_consumes           => 'application/xml'
    ,p_produces           => 'application/xml');

  xxas_com_sr_pkg.set_rest_method
    (p_service_name       => l_SERVICE
    ,p_method_name        => 'SaveForm'
    ,p_description        => 'Accepts posted forms and processes them'
    ,p_methods            => 'POST'
    ,p_plsql              =>
      q'[
				  DECLARE
          
         
          l_resp       		xxas_http_resp_obj;
          l_request_xml   XMLType;
          l_response_xml  XMLType;
          
        BEGIN
				
          l_request_xml := {requestBody};
        
          --
          -- This is checking the user has access to POST to this function
          -- and also validates data security
          -- (eg, that the user isn''t posting data for someone else).
          --
					IF xxas_emp_menu_pkg.has_access_to_function_flag
              (p_function_id => {pathParam.functionId}
              ,p_keys        => xxas_emp_view_ui_pkg.get_keys_from_form
                                  (p_function_id   => {pathParam.functionId}
                                  ,p_form_data_xml => l_request_xml)
               ) = 'N'
          THEN
            l_resp := xxas_http_response
                        .status(xxas_http_resp_status_pkg.unauthorised)
                        .build();
					ELSE

            xxas_emp_view_ui_pkg.save_form
              (p_function_id   => {pathParam.functionId}
              ,p_form_data_xml => l_request_xml
              ,p_response_xml  => l_response_xml);

            IF l_response_xml IS NULL THEN
						  l_resp := xxas_http_response.ok().build();            
            ELSE
						  l_resp := xxas_http_response.ok(l_response_xml).build();
            END IF;
            
					END IF;
          
				 {response} := l_resp;
          
				END
			]'
		);

END;
/
COMMIT;
EXIT;
