/**
 * Warranty & Liability
 * To the extent permitted by applicable law and unless explicitly
 * otherwise agreed upon, XLOG Technologies AG makes no warranties
 * regarding the provided information. XLOG Technologies AG assumes
 * no liability that any problems might be solved with the information
 * provided by XLOG Technologies AG.
 *
 * Rights & License
 * All industrial property rights regarding the information - copyright
 * and patent rights in particular - are the sole property of XLOG
 * Technologies AG. If the company was not the originator of some
 * excerpts, XLOG Technologies AG has at least obtained the right to
 * reproduce, change and translate the information.
 *
 * Reproduction is restricted to the whole unaltered document. Reproduction
 * of the information is only allowed for non-commercial uses. Selling,
 * giving away or letting of the execution of the library is prohibited.
 * The library can be distributed as part of your applications and libraries
 * for execution provided this comment remains unchanged.
 *
 * Restrictions
 * Only to be distributed with programs that add significant and primary
 * functionality to the library. Not to be distributed with additional
 * software intended to replace any components of the library.
 *
 * Trademarks
 * Jekejeke is a registered trademark of XLOG Technologies AG.
 */

:- ensure_loaded(library(util/sequence)).
:- ensure_loaded(library(text/format)).
:- ensure_loaded(library(text/catalog)).
:- ensure_loaded(library(tester/tools)).
:- ensure_loaded(library(compat)).

% sys_meta_args(+Atom, +Integer, -List)
:- multifile(sys_meta_args/3).

% time measurement
sys_meta_args(time, 1, [g]).
sys_meta_args(time, 2, [g,t]).

/*********************************************************************/
/* Statistics                                                        */
/*********************************************************************/

/**
 * statistics(K, V):
 * The predicate succeeds for the value V of the flag K. See
 * documentation for the available flags.
 */
% statistics(-Atom, -Term)
statistics(Key, Value) :- var(Key), !,
   os_stat_map(Map),
   os_obj_keys(Map, Keys),
   member(Key, Keys),
   os_obj_current(Map, Key, Value).
statistics(Key, Value2) :-
   os_stat_map(Map),
   os_obj_current(Map, Key, Value), !,
   Value2 = Value.
statistics(Key, _) :-
   throw(error(domain_error(prolog_flag, Key),_)).

/**
 * statistics:
 * The predicate displays the current statistics key value pairs.
 */
% statistics
statistics :-
   current_output(Stream),
   statistics(K, V),
   put_message(Stream, statistics(K,V)), nl,
   fail.
statistics.

/*********************************************************************/
/* Time Measurement                                                  */
/*********************************************************************/

/**
 * time(G):
 * time(G, F):
 * The predicate succeeds whenever the goal G succeeds. As a
 * side effect, timing of the call or redo is shown. The binary
 * predicate allows specifying a format atom F.
 */
% time(+Goal)
time(Goal) :-
   get_message(time(fields), Format),
   time(Goal, Format).

% time(+Goal, +Atom)
time(Goal, Format) :-
   atom_codes(Format, Codes),
   State =.. [v,0,0,0,0],
   try_call_finally(
      sys_time_set(State),
      Goal,
      sys_time_show(State, Codes)).

% sys_time_set(+Compound)
sys_time_set(State) :-
   os_stat_map(Map),
   os_obj_current(Map, time, Time),
   os_obj_current(Map, user, User),
   os_obj_current(Map, gctime, Gctime),
   os_obj_current(Map, calls, Calls),
   change_arg(1, State, Time),
   change_arg(2, State, User),
   change_arg(3, State, Gctime),
   change_arg(4, State, Calls).

% sys_time_show(+Compound, +List)
sys_time_show(State, Codes) :-
   arg(1, State, Time2),
   arg(2, State, User2),
   arg(3, State, Gctime2),
   arg(4, State, Calls2),
   os_stat_map(Map),
   os_obj_current(Map, time, Time),
   os_obj_current(Map, user, User),
   os_obj_current(Map, gctime, Gctime),
   os_obj_current(Map, calls, Calls),
   Time3 is Time-Time2,
   User3 is User-User2,
   Gctime3 is Gctime-Gctime2,
   Calls3 is Calls-Calls2,
   (Time3 =\= 0 -> Perc is round(User3*100/Time3); Perc = 100),
   (User3 =\= 0 -> Lips is round(Calls3/User3); Lips = 0),
   current_output(Stream),
   sys_time_format(Stream, [t-Time3, g-Gctime3, p-Perc, l-Lips], Codes, []),
   nl.

% sys_time_format(+Stream, +Map, +List, -List)
sys_time_format(Stream, Map) --> [0'%, Code],
   {char_code(Key, Code), member(Key-Value, Map)}, !,
   {put_message(Stream, time(field,Key,Value))},
   sys_time_format(Stream, Map).
sys_time_format(Stream, Map) --> [Code], !,
   {char_code(Char, Code), put_atom(Stream, Char)},
   sys_time_format(Stream, Map).
sys_time_format(_, _) --> [].

/*********************************************************************/
/* Listing Indexes                                                   */
/*********************************************************************/

/**
 * jiti_list:
 * jiti_list(I):
 * The predicate lists the index statictics of the user predicates.
 * The unary predicate allows specifying a predicate indicator.
 */
% jiti_list
jiti_list :-
   jiti_list(_).

% jiti_list(+Indicator)
jiti_list(I) :-
   current_output(Stream),
   sys_jiti_list(I, Stream).

% sys_jiti_list(+Indicator, +Stream)
sys_jiti_list(F/N, Stream) :- !,
   sys_jiti_list_pattern(F, N, Stream).
sys_jiti_list(F, Stream) :-
   sys_jiti_list_pattern(F, _, Stream).

% sys_jiti_list_pattern(+Atom, +Integer, +Stream)
sys_jiti_list_pattern(F, N, Stream) :-
   call_nth(sys_jiti_list_indicator(F, N), C),
   (C > 1 -> nl(Stream); true),
   sys_jiti_list_pred(F, N, Stream),
   fail.
sys_jiti_list_pattern(_, _, _).

% sys_jiti_list_pred(+Atom, +Integer, +Stream)
sys_jiti_list_pred(F, N, Stream) :-
   put_message(Stream, jiti_list(pred,F/N)),
   nl(Stream),
   ir_pred_link(F, N, Q),
   ir_link_flags(Q, D),
   (D /\ 16 =\= 0 -> T = 'prehash'; T = 'functor'),
   put_message(Stream, jiti_list(type,T)),
   nl(Stream),
   ir_link_stat_get(Q, M),
   os_obj_keys(M, L),
   member(I, L),
   os_obj_current(M, I, S),
   member(K-V, [path-I, size-S]),
   put_message(Stream, jiti_list(K,V)),
   nl(Stream),
   fail.
sys_jiti_list_pred(_, _, _).

/****************************************************************/
/* Indexes Filter                                               */
/****************************************************************/

% sys_jiti_list_indicator(-Atom, +Integer)
sys_jiti_list_indicator(F, N) :-
   current_predicate(F/N),
   ir_pred_link(F, N, Q),
   ir_link_stat_has(Q),
   \+ sys_user_stop(F, N),
   functor(H, F, N),
   \+ \+ sys_user_ref(H, _).

/*********************************************************************/
/* Other Texts                                                       */
/*********************************************************************/

% strings(+Atom, +Atom, -Atom)
:- multifile(strings/3).
strings('statistics.gctime', de, '% GC Zeit~t~3f~40| ms').
strings('statistics.maxinfs', de,'% Autoyield~t~d~40|').
strings('statistics.calls', de,  '% Aufrufe~t~d~40|').
strings('statistics.time', de,   '% Betriebszeit~t~3f~40| ms').
strings('statistics.user', de,   '% Benutzerzeit~t~3f~40| ms').
strings('statistics.wall', de,   '% Uhrzeit~t~d~40| ms').
strings('statistics.used', de,   '% Belegter Speicher ~t~d~40| B').
strings('statistics.maxmem', de, '% Zugewiesener Speicher ~t~d~40| B').

strings('time.fields', de, '% %t, %p, %l').
strings('time.field.t', de, 'Zeit ~3f ms').
strings('time.field.g', de, 'GC ~3f ms').
strings('time.field.p', de, 'Benutzer ~d %').
strings('time.field.l', de, 'Lips ~d k').

strings('jiti_list.pred', de,    '% Prädikat~t~w~40|').
strings('jiti_list.type', de,    '% Typ~t~w~40|').
strings('jiti_list.path', de,    '% Argumente~t~w~40|').
strings('jiti_list.size', de,    '% Kardinalität~t~d~40|').

strings('statistics.gctime', '', '% GC time~t~3f~40| ms').
strings('statistics.maxinfs', '','% Autoyield~t~d~40|').
strings('statistics.calls', '',  '% Calls~t~d~40|').
strings('statistics.time', '',   '% Realtime~t~3f~40| ms').
strings('statistics.user', '',   '% Usertime~t~3f~40| ms').
strings('statistics.wall', '',   '% Walltime~t~d~40| ms').
strings('statistics.used', '',   '% Used Memory~t~d~40| B').
strings('statistics.maxmem', '', '% Assigned Memory~t~d~40| B').

strings('time.fields', '', '% %t, %p, %l').
strings('time.field.t', '', 'Time ~3f ms').
strings('time.field.g', '', 'GC ~3f ms').
strings('time.field.p', '', 'User ~d %').
strings('time.field.l', '', 'Lips ~d k').

strings('jiti_list.pred', '',    '% Predicate~t~w~40|').
strings('jiti_list.path', '',    '% Type~t~w~40|').
strings('jiti_list.type', '',    '% Arguments~t~w~40|').
strings('jiti_list.size', '',    '% Cardinality~t~d~40|').

/*********************************************************************/
/* Error Texts                                                       */
/*********************************************************************/

strings('resource_error.expose_gc', de, 'Host Speicherbereinigung nicht freigelegt.').

strings('resource_error.expose_gc', '', 'Host garbage collection not exposed.').

/*******************************************************************/
/* Foreign Predicates                                              */
/*******************************************************************/

% os_stat_map(X):
% defined in foreign(tester/statlib)

% garbage_collect:
% defined in foreign(tester/statlib)

% ir_link_stat_has(Q):
% defined in foreign(tester/statlib)

% ir_link_stat_get(Q, M):
% defined in foreign(tester/statlib)

:- ensure_loaded(foreign(tester/statlib)).