/**
  @file restore.sas
  @brief Restores a data version
  @details Only applies if the history is stored in the audit table

  <h4> SAS Macros </h4>
  @li dc_assignlib.sas
  @li mcf_getfmttype.sas
  @li mf_nobs.sas
  @li mp_abort.sas
  @li mp_applyformats.sas
  @li mp_ds2csv.sas
  @li mp_getcols.sas
  @li mp_stripdiffs.sas
  @li mpeinit.sas
  @li mpe_checkrestore.sas
  @li mpe_loader.sas

  <h4> Service Inputs </h4>
  <h5> restore_in </h5>

  |LOAD_REF:$32|
  |---|
  |DCXXXXXX|

  @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.

**/

%mpeinit()

%let loadref=;
data _null_;
  set work.restore_in;
  call symputx('loadref',load_ref);
run;

/**
  * Check if user has basic access permission to RESTORE the table
  */
%put checking access;
%global allow_restore reason;
%mpe_checkrestore(&loadref,outresult=ALLOW_RESTORE,outreason=REASON)

%mp_abort(iftrue= (&ALLOW_RESTORE ne YES)
  ,mac=&_program..sas
  ,msg=%str(Cannot restore because: &reason)
)

/* grab the base DS */
proc sql noprint;
select cats(base_lib,'.',base_ds) into: tgtds
  from &mpelib..mpe_submit
  where TABLE_ID="&loadref";

/* find the audit table */
select coalescec(audit_libds,"&mpelib..MPE_AUDIT"), loadtype, var_txto
  into: difftable, :loadtype, :txto
  from &mpelib..MPE_TABLES
  where libref="%scan(&tgtds,1,.)"
        & dsn="%scan(&tgtds,2,.)"
        & &dc_dttmtfmt<tx_to;
%mp_abort(iftrue= ("&difftable"="0")
  ,mac=&_program..sas
  ,msg=%str(No audit table configured for &tgtds)
)

/* assign the library */
%dc_assignlib(READ,%scan(&tgtds,1,.))

/* if the target is an SCD2 table, create a view to get current snapshot */
%let fltr=%sysfunc(ifc(&loadtype=TXTEMPORAL,&dc_dttmtfmt<&txto,1=1));

/* extract the differences to be applied */
%mp_stripdiffs(&tgtds,&loadref,&difftable
  ,outds=work.mp_stripdiffs
  ,filtervar=fltr
  ,mdebug=&sasjs_mdebug
)

/* abort if any issues */
%mp_abort(iftrue= (&syscc>0)
  ,mac=&_program..sas
  ,msg=%str(syscc=&syscc after stripdiffs)
)
%mp_abort(iftrue= (%mf_nobs(work.mp_stripdiffs)=0)
  ,mac=&_program..sas
  ,msg=%str(THERE ARE NO DIFFERENCES TO APPLY)
)

/* create a new load ref */
%let mperef=DC%left(%sysfunc(datetime(),B8601DT19.3))_%substr(
  %sysfunc(ranuni(0)),3,6)_%substr(%str(&sysjobid    ),1,4);

/* Create package folder */
%let dir=&mpelocapprovals/&mperef;
%mf_mkdir(&dir)
options notes mprint;
libname approve "&dir";

/* take copy of macvars */
data _null_;
  file "&dir/macvars.sas";
  set sashelp.vmacro;
  where scope='GLOBAL';
  put '%let ' name '=' value ';';
run;

/* copy the diffs dataset */
data approve.jsdset;
  length _____DELETE__THIS__RECORD_____ $3;
  if 0 then call missing(_____DELETE__THIS__RECORD_____);
  set work.mp_stripdiffs;
  format _all_;
run;

/* find all of the date / datetime / time vars */
%mcf_getfmttype(wrap=YES)
%mp_getcols(&tgtds,outds=work.cols)

data work.applydtfmts;
  set work.cols;
  lib="APPROVE";
  ds="JSDSET";
  var=name;
  fmt=coalescec(format,'0');
  fmttype=mcf_getfmttype(fmt);
  if fmttype in ('DATE','DATETIME','TIME');
  keep lib ds var fmt;
run;
%mp_applyformats(work.applydtfmts)


/* export to csv */
%mp_ds2csv(approve.jsdset
  ,dlm=COMMA
  ,outfile="&dir/%trim(&tgtds).csv"
  ,outencoding="UTF-8"
  ,headerformat=NAME
  ,termstr=CRLF
)

%mp_abort(iftrue= (&syscc ne 0)
  ,mac=&_program
  ,msg=%str(syscc=&syscc when writing the CSV)
)

%mpe_loader(mperef=&mperef
  ,submitted_reason_txt=Restoring &loadref
  ,dc_dttmtfmt=&dc_dttmtfmt
)
%mp_abort(mode=INCLUDE)

%mp_abort(
  iftrue=(%sysfunc(fileexist(%sysfunc(pathname(work))/mf_abort.error))=1)
  ,mac=&_program..sas
  ,msg=%str(mf_abort.error=1)
)

%mp_abort(iftrue= (&syscc ne 0)
  ,mac=&_program..sas
  ,msg=%str(syscc=&syscc)
)

/* send relevant SUCCESS values */
data work.restore_out;
  loadref="&mperef";
run;


%webout(OPEN)
%webout(OBJ,restore_out)
%webout(CLOSE)

