/**
  @file
  @brief testing postdata with mpe_x_test

  <h4> SAS Macros </h4>
  @li mx_testservice.sas
  @li mp_assert.sas


**/


/**
  * First part - stage some data (for diffing)
  */
data work.sascontroltable;
  action='LOAD';
  message="getdiffs prep";
  libds="&dclib..MPE_X_TEST";
  output;
  stop;
run;

proc sql noprint;
select max(primary_key_field) into: maxpk
  from &dclib..mpe_x_test;

data work.jsdata;
  set &dclib..mpe_x_test(rename=(
    some_date=dt2 SOME_DATETIME=dttm2 SOME_TIME=tm2)
  );
  /* for now, the adapter sends these as strings */
  some_date=put(dt2,date9.);
  SOME_DATETIME=put(dttm2,datetime19.);
  some_time=put(tm2,time.);
  drop dt2 dttm2 tm2;
  if _n_=1 then do;
    _____DELETE__THIS__RECORD_____='Yes';
    output;
    _____DELETE__THIS__RECORD_____='No';
    some_char='   leadingblanks';
    some_bestnum=._;
    /* modify 1 record and add 4 more */
    do primary_key_field=&maxpk to (&maxpk+5);
      some_num=ranuni(0);
      output;
    end;
  end;
  else stop;
run;

%mx_testservice(&appLoc/services/editors/stagedata,
  viyacontext=&defaultcontext,
  inputdatasets=work.jsdata work.sascontroltable,
  outlib=web1,
  mdebug=&sasjs_mdebug
)

%let status=0;
data _null_;
  set web1.sasparams;
  putlog (_all_)(=);
  if status='SUCCESS' then call symputx('status',1);
  call symputx('dsid',dsid);
run;

%mp_assert(
  iftrue=(&status=1 and &syscc=0),
  desc=Checking successful submission
)

/**
  * Now run postdata with SHOW_DIFFS
  */
data work.sascontroltable;
  ACTION='SHOW_DIFFS';
  TABLE="&dsid";
  DIFFTIME="%sysfunc(datetime(),B8601DT19.3)";
  output;
  stop;
run;
%mx_testservice(&appLoc/services/auditors/postdata,
  viyacontext=&defaultcontext,
  inputdatasets=work.sascontroltable,
  outlib=web2,
  outref=wbout,
  mdebug=&sasjs_mdebug
)

%let leadcheck=0;
%let speshcheck=0;
data _null_;
  infile wbout;
  input;
  putlog _infile_;
  /* the JSON libname engine removes leading blanks!!!! */
  if index(_infile_,'   leadingblanks') then call symputx('leadcheck',1);
  /* there is no clean way to send a special missing - so is sent as string */
  if index(_infile_,',"SOME_BESTNUM":"_"') then call symputx('speshcheck',1);
run;


%mp_assert(
  iftrue=(&leadcheck=1),
  desc=Checking leading blanks were applied
)
%mp_assert(
  iftrue=(&leadcheck=1),
  desc=Checking special characters were applied
)

/* Now actually approve the table */
data work.sascontroltable;
  ACTION='APPROVE_TABLE';
  TABLE="&dsid";
  /* difftime is numeric for approve action */
  DIFFTIME="%sysfunc(datetime())";
  output;
  stop;
run;
%mx_testservice(&appLoc/services/auditors/postdata,
  viyacontext=&defaultcontext,
  inputdatasets=work.sascontroltable,
  outlib=web3,
  outref=wb3,
  mdebug=&sasjs_mdebug
)

%let status=0;
data _null_;
  set web3.apparams;
  putlog (_all_)(=);
  if response='SUCCESS!' then call symputx('status',1);
run;

%mp_assert(
  iftrue=(&status=1 and &syscc=0),
  desc=Checking successful submission
)