/**
  @file mpe_getlabels.sas
  @brief Gets the table and column labels for a particular table
  @details Builds a labels dataset by combining three inputs:

    @li NAME - taken from `source`.  This is typically a WORK subset of
      the underlying table (e.g. after column-level security has been
      applied) and dictates which columns appear in the output.
    @li MEMLABEL / LABEL - taken from `tgt_ds` (the two-part
      libref.dataset).  This ensures the "true" table and column
      labels are used rather than any that may have been stripped
      during WORK subsetting.
    @li DD_SHORTDESC / DD_LONGDESC - taken from `mpe_datadictionary`
      where DD_SOURCE contains the `LIB.DSN` reference and DD_TYPE is
      `COLUMN`.

  If `tgt_ds` is not supplied it defaults to `source`.

  @param [in] type The type of labels to fetch (only COLUMNS is
    currently supported).
  @param [in] source The dataset from which column NAMES are read.
  @param [in] tgt_ds= (&source) The two-part libref.dataset from which
    the table/column LABELS are read, and used when joining to
    `mpe_datadictionary` for short/long descriptions.
  @param [out] outds= (mpe_getlabels) The output dataset with columns
    `name`, `memlabel`, `desc`, `longdesc`.

  <h4> SAS Macros </h4>
  @li mf_getuniquename.sas

  @version 9.2
  @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 mpe_getlabels(type,source,tgt_ds=,outds=mpe_getlabels);
%local src_cols tgt_cols;

%if %superq(tgt_ds)= %then %let tgt_ds=&source;

%if &type=COLUMNS %then %do;
    %let src_cols=%mf_getuniquename();
    %let tgt_cols=%mf_getuniquename();

    /* NAMES from the (potentially filtered) source dataset */
    proc contents noprint data=&source
      out=&src_cols(keep=name);
    run;

    /* LABELS from the underlying target dataset */
    proc contents noprint data=&tgt_ds
      out=&tgt_cols(keep=name memlabel label);
    run;

    proc sql;
    create table &outds as
    select upcase(a.name) as name
        ,b.memlabel
        ,coalesce(c.dd_shortdesc,b.label) as desc
        ,c.dd_longdesc as longdesc
    from &src_cols a
    inner join &tgt_cols b
      on upcase(a.name)=upcase(b.name)
    left join &mpelib..mpe_datadictionary
        (where=(&dc_dttmtfmt. < tx_to
        and dd_source ? %upcase("&tgt_ds")
        and dd_type='COLUMN')) c
      on scan(c.dd_source,-1,'.')=upcase(a.name);
    quit;
%end;

%mend mpe_getlabels;
