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

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

DECLARE

  --
  -- Local constants and variables
  --
  e_no_bg_id          EXCEPTION;
  e_bg_not_exists     EXCEPTION;
  e_ff_type_not_found EXCEPTION;
  l_BG_ID   CONSTANT  NUMBER        := to_number('&1');
  l_USER_ID CONSTANT  NUMBER        := to_number('&2');
  l_START   CONSTANT  DATE          := to_date('1900-01-01','YYYY-MM-DD');
  l_END     CONSTANT  DATE          := xxas_util_pkg.eot;
  l_FF_NAME CONSTANT  VARCHAR2(80)  := 'XXAS_COM_AVAIL_ENR';
  l_FF_DESC CONSTANT  VARCHAR2(240) := 'Seeded enrollment availability formula';
  l_FF_TYPE CONSTANT  varchar2(30)  := 'QuickPaint';
  l_formula_text      LONG;
  l_formula_type_id   NUMBER;
  l_ff_id             NUMBER;
  l_bg_exists         VARCHAR2(1);

  --
  -- Gets the FF Id
  --
  CURSOR csr_ff_id IS
  SELECT ff.formula_id
  FROM   ff_formulas_f ff
  WHERE  ff.business_group_id = l_BG_ID
  AND    ff.formula_name = l_FF_NAME;

  --
  -- Tests if the Business Group already exists
  --
  CURSOR csr_bg_exists IS
  SELECT 'Y'
  FROM   per_business_groups_perf bg
  WHERE  bg.business_group_id = l_BG_ID;

  --
  -- Gets the Formula Type Id
  --
  CURSOR csr_ff_type IS
  SELECT fft.formula_type_id
  FROM   ff_formula_types fft
  WHERE  fft.formula_type_name = l_FF_TYPE;

BEGIN

  --
  -- Check that the Business Group Id was passed in
  --
  IF l_BG_ID IS NULL THEN
    RAISE e_no_bg_id;
  END IF;

  --
  -- Check the Business Group exists
  --
  OPEN  csr_bg_exists;
  FETCH csr_bg_exists INTO l_bg_exists;
  CLOSE csr_bg_exists;

  IF l_bg_exists IS NULL THEN
    RAISE e_bg_not_exists;
  END IF;

  --
  -- Fetch the Fast Formula Id
  --
  OPEN  csr_ff_id;
  FETCH csr_ff_id INTO l_ff_id;
  CLOSE csr_ff_id;

  --
  -- Get the Formula Type; error if it cannot be found
  --
  OPEN  csr_ff_type;
  FETCH csr_ff_type INTO l_formula_type_id;
  CLOSE csr_ff_type;

  IF l_formula_type_id IS NULL THEN
    RAISE e_ff_type_not_found;
  END IF;

  --
  -- Set the Formula Text
  --
  l_formula_text := '
/*==============================================================================

Formula Name: XXAS_COM_AVAIL_ENR
Formula Type: QuickPaint
Description:  Seeded enrollment availability formula.

==============================================================================*/


/* +-------------------< SECTION 1: DEFAULTS >-------------------------------+
   Defaults must be specified for every item listed in the Inputs section. When
   a value is not set on the enrollment it will be defaulted to the default
   specified here.                                                          */

  Default for Event_Id                 is -1
  Default for Session_or_Scheduled     is ''Unknown''
  Default for Course_Name              is ''Unknown''
  Default for Class_Name               is ''Unknown''
  Default for Enrollment_Status        is ''Unknown''
  Default for Enrollment_Status_Code   is ''Unknown''
  Default for Delivery_Mode            is ''Unknown''
  Default for Start_Date               is ''0001/01/01 00:00:00'' (date)
  Default for End_Date                 is ''4712/12/31 00:00:00'' (date)
  Default for Start_Time               is ''Unknown''
  Default for End_Time                 is ''Unknown''


/* +-------------------< SECTION 2: INPUTS >---------------------------------+
   This formula lists all the available items that you can use in this
   type of formula.                                                         */

  Inputs are Event_Id, Session_or_Scheduled,
             Course_Name, Class_Name,
             Enrollment_Status, Enrollment_Status_Code, Delivery_Mode,
             Start_Date (date), End_Date (date), Start_Time, End_Time


/* +-------------------< SECTION 3: OTHER DEFAULTS >-------------------------+
   It is good practice to define default values for the Formula Outputs and
   other variables that are used in this formula.  This helps to guard against
   empty outputs being returned and keeps the formula tidy.

   The Formula Outputs are the reason for this Formula: it gives you finite
   control to set the Outputs to whatever values you choose.  You can use
   information in the Formula Inputs to conditionally set the Outputs - you
   can see examples of this in Section 4.

   Here they are defaulted to initial values and later tweaked.             */

  Free_Busy  = ''Do Not Disturb'' /* Choose from Busy, Free, Tentative, Do Not
                                   Disturb, Invisible and Unknown.  Invisible
                                   forces the enrollment to be ignored so in
                                   this case other Outputs have no purpose. */
  Color        = ''#FF0011''      /* Choose from Aqua, Black, Blue, Fuchsia,
                                   Gray, Green, Lime, Maroon, Navy, Olive,
                                   Purple, Red, Silver, Teal, White, and
                                   Yellow.                                  */
  Availability = ''In Training''  /* A title for the Free_Busy status. You can
                                   use any text, such as ''Out the Office''.  */
  Description  = ''Placeholder''  /* This is set in section 4 - see below for
                                   details.                                 */
  Icon         = ''MORTARBOARD''  /* Set to the name of the availability icon
                                   you wish to set. Optional.               */


/* +-------------------< SECTION 4: MAIN LOGIC >-----------------------------+
   This contains logic that adjusts the Outputs according to certain
   conditions.  For example, the below builds a dynamic string for the
   Description.                                                             */

  /* Set the first part of the description and ignore the training if
     it''s not one of the below statuses */
  If upper(Enrollment_Status) like ''REQUESTED'' Or
          upper(Enrollment_Status) like ''WAITLISTED'' Then
    (
    Desc_Text = xxas_get_message(''XXAS'',''XXAS_EMP_ABS_DESC_TEXT_IX'')
    Free_Busy = ''Tentative''
    Color = ''#FF9900''
    )
  Else If upper(Enrollment_Status) like ''PLACED'' OR
          upper(Enrollment_Status) like ''ENROLLED''  Then
    (Desc_Text = xxas_get_message(''XXAS'',''XXAS_EMP_ABS_DESC_TEXT_X''))
  Else
    (
     Desc_Text = xxas_get_message(''XXAS'',''XXAS_EMP_UNKNOWN'')
     Free_Busy = ''Invisible''
    )

  /* Include the end date and time if set */
      If End_Date was not defaulted Then
        (
        Return_Text = xxas_get_message(''XXAS'',''XXAS_EMP_UNTIL'')
        If End_Time was not defaulted Then
          (Return_Text = Return_Text + '' '' + End_Time + xxas_get_message

(''XXAS'',''XXAS_EMP_ON''))
        Return_Text = xxas_get_message

(''XXAS'',''XXAS_EMP_UNTIL_THE'',''END_DATE'',to_char(End_Date, ''DD Month''))
        )
      Else
        (Return_Text = xxas_get_message(''XXAS'',''XXAS_EMP_RETURN_TEXT''))

  /* Bring the description together */
  Description = Desc_Text + '' '' + Return_Text


/* +-------------------< SECTION 5: RETURN OUTPUTS >-------------------------+
   This section returns the Outputs.  All 4 Outputs must be returned with
   a value.                                                                 */

RETURN Free_Busy, Color, Availability, Icon, Description

';


  BEGIN

    IF l_ff_id IS NULL THEN
      --
      -- Create the Fast Formula
      --
      INSERT INTO ff_formulas_f
        (formula_id
        ,effective_start_date
        ,effective_end_date
        ,business_group_id
        ,formula_type_id
        ,formula_name
        ,description
        ,formula_text)
      VALUES
        (ff_formulas_s.nextval
        ,l_START
        ,l_END
        ,l_BG_ID
        ,l_formula_type_id
        ,l_FF_NAME
        ,l_FF_DESC
        ,l_formula_text);

    ELSE
      --
      -- Update the existing Fast Formula text
      -- (if it has multiple date-track versions the text of
      -- all versions is updated).
      --
      UPDATE ff_formulas_f
      SET    formula_text = l_formula_text
            ,description  = l_FF_DESC
      WHERE  formula_id = l_ff_id;

    END IF;

    COMMIT;

    EXCEPTION
      WHEN others THEN
        ROLLBACK;
        RAISE;
    END;

    --
    -- Compile the Fast Formula
    --
    xxas_util_pkg.compile_ff
      (p_user_id => l_USER_ID
      ,p_ff_type => l_FF_TYPE
      ,p_ff_name => l_FF_NAME);

EXCEPTION

  WHEN e_no_bg_id THEN
    RAISE no_data_found;

  WHEN e_bg_not_exists THEN
    RAISE no_data_found;

  WHEN e_ff_type_not_found THEN
    RAISE no_data_found;

END;
/
COMMIT;
EXIT;
