/**
  @file
  @brief Loads a CAS table into memory
  @details There are three versions of this macro, one per build
    target.  The interface is the same.  The macro loads the source table
    to memory (if not loaded) and promotes it.

    Note that we cannot collect metadata from the APIs (like in
    mv_castabload) because the server info may be inacessible to
    the logged in user

    Running SAS code under a system account (like proc util) DOES
    work, so we just make the assumption that the source file and
    library matches the libds.

  @param [in] libds   library.dataset of the CAS table to load
  @param [in] mdebug= (0) Set to 1 to enable verbose logging

  <h4> SAS Macros </h4>
  @li mf_getengine.sas
  @li mfv_getcaslib.sas
  @li mp_abort.sas

  @author 4GL Apps Ltd
  @copyright 4GL Apps Ltd.  This code may only be used within Data
    Controller and may not be re-distributed or re-sold without the
    express permission of 4GL Apps Ltd.
**/

%macro dc_casload(libds, mdebug=0);
  %local lib eng caslib ds _exists;

  %mp_abort(
    iftrue=(&syscc ne 0),
    msg=%str(syscc=&syscc on macro entry)
  )

  %let lib=%scan(&libds,1,.);
  %let eng=%mf_getengine(&lib);
  %mp_abort(iftrue= (X&eng.X=XX)
    ,mac=&_program
    ,msg=%str(Library &lib is not assigned)
  )

  %if &eng ne CAS %then %return;

  %let caslib=%mfv_getcaslib(lib=&lib);
  %let ds=%scan(&libds,2,.);
  %if &mdebug=1 %then %put _local_;
  /* ---- existence check ------------------------------------------------- */
  proc cas;
    table.tableExists result=r /
        caslib="&caslib"
        name="&ds";
    %if &mdebug=1 %then %do;
      print r;
    %end;
    if r.exists > 0 then call symputx('_exists', '1', 'L');
    else call symputx('_exists', '0', 'L');
  quit;

  /* ---- already loaded: skip -------------------------------------------- */
  %if &_exists=1 %then %do;
    %put NOTE: Table &caslib..&ds already loaded - skipping;
    %return;
  %end;

  proc casutil;
    load casdata="&ds"
        incaslib="&caslib"
        casout="&ds"
        outcaslib="&caslib"
        promote;
  quit;

  %mp_abort(
    iftrue=(&syscc ne 0),
    msg=%str(Load failed for &caslib..&ds)
  )

  %put NOTE: Table &caslib..&ds loaded and promoted;

%mend dc_casload;
