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

  xxas_com_sr_pkg.set_rest_service
    (p_service_name       => l_SERVICE
    ,p_description        => 'View and change a person''s photo'
    ,p_path               => '/people/{personId}/photo'
    ,p_consumes           => 'image/*'
    ,p_produces           => 'image/*'
    );

  xxas_com_sr_pkg.set_rest_method
    (p_service_name       => l_SERVICE
    ,p_method_name        => 'GetPersonPhotos'
    ,p_description        => 'Get a person''s photos and available operations'
    ,p_methods            => 'GET'
    ,p_consumes           => 'application/xml'
    ,p_produces           => 'application/xml'
    ,p_remove_root_ele    => true
    ,p_sql                =>
      q'[
        SELECT XMLElement
                ("data"
                ,XMLForest
                  (xxas_com_rest_util_pkg.uri_from_path('people/' || {pathParam.personId} || '/photo') "self"
                  ,xxas_util_pkg.get_initials(img.first_name, img.last_name, img.known_as) "initials"
                  ,xxas_per_image_pkg.url(img.person_id, img.last_update_date, 'SMALL') "small"
                  ,xxas_per_image_pkg.url(img.person_id, img.last_update_date, 'MEDIUM') "medium"
                  ,xxas_per_image_pkg.url(img.person_id, img.last_update_date, 'FULL_SIZE') "fullSize"
                  )
                ,CASE WHEN update_allowed = 'N' AND delete_allowed = 'N' THEN
                    NULL
                 ELSE
                    XMLElement
                      ("meta"
                      ,XMLElement
                        ("operations"
                        ,CASE WHEN update_allowed = 'N' THEN
                          NULL
                         ELSE
                            XMLElement
                              ("POST"
                              ,XMLForest
                                (xxas_com_msg_pkg.get_string('XXAS_RB_DIR_CHOOSE_PHOTO') "title"
                                ,'positive' "color"
                                ,xxas_com_rest_util_pkg.uri_from_path('people/' || img.person_id || '/photo?fileName={fileName}&amp;fileMimeType={fileMimeType}') "href"
                                )
                              ,XMLElement
                                ("validation"
                                ,XMLElement
                                  ("fileSize"
                                  ,XMLForest
                                    (fnd_profile.value('UPLOAD_FILE_SIZE_LIMIT') "arguments"
                                    ,xxas_com_msg_pkg.get_string('XXAS_RB_COM_MAX_SIZE') "error")
                                  )
                                ,XMLElement
                                  ("fileExtension"
                                  ,XMLForest
                                    ('image/jpeg' "arguments"
                                    ,xxas_com_msg_pkg.get_string('XXAS_RB_COM_EXT_ERR') "error")
                                  )
                                )
                              )
                         END
                        ,CASE WHEN delete_allowed = 'N' THEN
                           NULL
                         ELSE
                           XMLElement
                            ("DELETE"
                            ,XMLForest
                              (xxas_com_msg_pkg.get_string('XXAS_RB_DIR_DELETE_PHOTO') "title"
                              ,'assertive' "color"
                              ,xxas_com_rest_util_pkg.uri_from_path('people/' || img.person_id || '/photo') "href"
                              )
                            )
                         END
                        )
                      )
                 END
                ) "data"
        FROM  (SELECT {pathParam.personId} person_id
                     ,t2.first_name
                     ,t2.last_name
                     ,t2.known_as
                     ,t2.last_update_date
                     ,decode
                       (nvl(lower({requestParam.includeEdits}), 'true')
                       ,'false'
                       ,'N'
                       ,xxas_com_sec_pkg.test_instance
                         ('XXAS_EMP_UPL_PHOTO_PERM', {pathParam.personId})) update_allowed
                     ,decode
                       (t2.last_update_date
                       ,null
                       ,'N'
                       ,decode
                         (nvl(lower({requestParam.includeEdits}), 'true')
                         ,'false'
                         ,'N'
                         ,xxas_com_sec_pkg.test_instance
                           ('XXAS_EMP_DEL_PHOTO_PERM', {pathParam.personId}))) delete_allowed
               FROM  (SELECT t.person_id
                            ,t.last_update_date
                            ,papf.first_name
                            ,papf.last_name
                            ,papf.known_as
                      FROM   xxas_per_thumbnails t
                            ,per_all_people_f papf
                      WHERE  t.person_id(+) = papf.person_id
                       AND  ( (trunc(sysdate) BETWEEN
               papf.effective_start_date AND papf.effective_end_date)  OR 
			   ( papf.effective_start_date > trunc(sysdate) AND 
			   papf.effective_start_date = (select min(papf2.effective_start_date) 
			   FROM per_all_people_f papf2 
			   WHERE papf2.person_id = {pathParam.personId} ) ))
                      AND    papf.person_id = {pathParam.personId}) t2
                      
                      
              ) img
        ]'        
    );
    
  xxas_com_sr_pkg.set_rest_method
    (p_service_name       => l_SERVICE
    ,p_method_name        => 'GetPersonPhoto'
    ,p_description        => 'Get a person''s photo'
    ,p_path               => '{photoId}/{size}'
    ,p_methods            => 'GET'
    ,p_sql                =>
      q'[SELECT xxas_http_response.ok()
               .expires(add_months(sysdate, 12))
               .entity(i.image, i.mime_type)
               .build() "httpResponse"
         FROM   TABLE(xxas_per_image_pkg.image_tbl({pathParam.personId}, {pathParam.size})) i
         WHERE  xxas_util_pkg.md5(i.last_update_date) = {pathParam.photoId}
		 AND     xxas_com_sec_pkg.test_instance(''XXAS_EMP_VIEW_PHOTO_PERM'', {pathParam.personId}) = ''Y''
       ]'        
    );

  xxas_com_sr_pkg.set_rest_method
    (p_service_name       => l_SERVICE
    ,p_method_name        => 'SetPersonPhoto'
    ,p_description        => 'Sets the person''s photo'
    ,p_methods            => 'POST'
    ,p_plsql              =>
      q'[
        DECLARE
          l_resp xxas_http_resp_obj;
          l_self varchar2(1000);
          
        BEGIN
       
          IF NOT xxas_com_sec_pkg.test_instance_rtn_boolean
            ('XXAS_EMP_UPL_PHOTO_PERM', {pathParam.personId}) THEN
            l_resp := xxas_http_response
                        .status(xxas_http_resp_status_pkg.unauthorised)
                        .build();
          ELSE
            l_self := 'people/' || {pathParam.personId} || '/photo';
            xxas_per_image_pkg.update_image
                     (pPersonId => {pathParam.personId}
                     ,pImage    => xxas_util_pkg.decode_blob({requestBody})
                     ,pFileName => {requestParam.fileName}
                     ,pFileMimeType => {requestParam.fileMimeType}										 
										 );
            l_resp := xxas_http_response
                        .created(xxas_com_rest_util_pkg.uri_from_path(l_self))
                        .entity(xxas_com_rest_mgr_pkg.get_xml_entity(l_self))
                        .build();
          END IF;
         
          {response} := l_resp;

        END
      ]'
    );
    
  xxas_com_sr_pkg.set_rest_method
    (p_service_name       => l_SERVICE
    ,p_method_name        => 'DeletePersonPhoto'
    ,p_description        => 'Delete a person''s Photo'
    ,p_methods            => 'DELETE'
    ,p_plsql              =>
      q'[
        DECLARE
          l_resp    xxas_http_resp_obj;
        BEGIN
       
          IF NOT xxas_com_sec_pkg.test_instance_rtn_boolean
            ('XXAS_EMP_DEL_PHOTO_PERM', {pathParam.personId}) THEN
            l_resp := xxas_http_response
                        .status(xxas_http_resp_status_pkg.unauthorised)
                        .build();
          ELSE
            xxas_per_image_pkg.delete_image
                     (pPersonId => {pathParam.personId});
            l_resp := xxas_http_response
                        .status(xxas_http_resp_status_pkg.no_content)
                        .build();
          END IF;
         
          {response} := l_resp;

        END
      ]'
    );

END;
/
COMMIT;
EXIT;
