/**
  @file
  @brief Post Edit Hook script for the MPE_XLMAP_INFO table
  @details Post edit hooks provide additional backend validation for user
  provided data.  The incoming dataset is named `work.staging_ds` and is
  provided in mpe_loader.sas.

  Available macro variables:
    @li DC_LIBREF - The DC control library
    @li LIBREF - The library of the dataset being edited (is assigned)
    @li DS - The dataset being edited

  <h4> SAS Macros </h4>
  @li mf_existds.sas
  @li mf_getvarlist.sas
  @li mf_wordsinstr1butnotstr2.sas
  @li dc_assignlib.sas
  @li mp_validatecol.sas

**/

data work.staging_ds;
  set work.staging_ds;

  /* apply the first excel map to all cells */
  length tgtds $41;
  retain tgtds;
  drop tgtds is_libds;
  if _n_=1 then do;
    if missing(XLMAP_TARGETLIBDS) then tgtds="&dc_libref..MPE_XLMAP_DATA";
    else tgtds=upcase(XLMAP_TARGETLIBDS);
    %mp_validatecol(XLMAP_TARGETLIBDS,LIBDS,is_libds)
    call symputx('tgtds',tgtds);
    call symputx('is_libds',is_libds);
  end;
  XLMAP_TARGETLIBDS=tgtds;

run;

%mp_abort(iftrue=(&is_libds ne 1)
  ,mac=mpe_xlmap_info_postedit
  ,msg=Invalid target dataset (&tgtds)
)

/**
  * make sure that the supplied target dataset exists and
  * has the necessary columns
  */
%dc_assignlib(READ,%scan(&tgtds,1,.))

%mp_abort(iftrue=(%mf_existds(libds=&tgtds) ne 1)
  ,mac=mpe_xlmap_info_postedit
  ,msg=Target dataset (&tgtds) could not be opened
)

%let tgtvars=%upcase(%mf_getvarlist(&tgtds));
%let srcvars=%upcase(%mf_getvarlist(&dc_libref..MPE_XLMAP_DATA));
%let badvars1=%mf_wordsInStr1ButNotStr2(Str1=&srcvars,Str2=&tgtvars);
%let badvars2=%mf_wordsInStr1ButNotStr2(Str1=&tgtvars,Str2=&srcvars);

%mp_abort(iftrue=(%length(&badvars1.X)>1)
  ,mac=mpe_xlmap_info_postedit
  ,msg=%str(Target dataset (&tgtds) has missing vars: &badvars1)
)

%mp_abort(iftrue=(%length(&badvars2.X)>1)
  ,mac=mpe_xlmap_info_postedit
  ,msg=%str(Target dataset (&tgtds) has unrecognised vars: &badvars2)
)