/**
 * 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.
 */

/**
 * delete_file(F):
 * The predicate succeeds. As a side effect the file F
 * is deleted. If the effect cannot be produced, the
 * predicate will throw an exception.
 */
% delete_file(+Atom)
delete_file(F) :-
   os_unlink_sync(F, E),
   (E = '' ->
       true;
    E = 'ENOENT' ->
       throw(error(existence_error(source_sink,F),_));
    E = 'EISDIR' ->
       throw(error(permission_error(delete,file,F),_));
    throw(error(resource_error(io_exception),_))).

/**
 * remove_directory(F):
 * The predicate succeeds. As a side effect the directory F
 * is removed. If the effect cannot be produced, the
 * predicate will throw an exception.
 */
% remove_directory(+Atom)
remove_directory(F) :-
   os_rmdir_sync(F, E),
   (E = '' ->
       true;
    (E = 'ENOENT'; E = 'ENOTDIR') ->
       throw(error(existence_error(directory,F),_));
    (E = 'ENOTEMPTY'; E = 'EEXIST') ->
       throw(error(permission_error(remove,directory,F),_));
    throw(error(resource_error(io_exception),_))).

/**
 * make_directory(F, E):
 * The predicate succeeds. As a side effect the directory F
 * is created. If the effect cannot be produced, the
 * predicate will throw an exception.
 */
% make_directory(+Atom)
make_directory(F) :-
   os_mkdir_sync(F, E),
   (E = '' ->
       true;
    (E = 'ENOENT'; E = 'ENOTDIR') ->
       file_directory_name(F, H),
       throw(error(existence_error(directory,H),_));
    E = 'EEXIST' ->
       throw(error(permission_error(create,directory,F),_));
    throw(error(resource_error(io_exception),_))).

/**
 * directory_files(F, L):
 * The predicate succeeds in L with the file and directory
 * entries of the directory F. If the list cannot be produced,
 * the predicate will throw an exception.
 */
% directory_files(+Atom, -List)
directory_files(F, L) :-
   os_readdir_sync(F, H, E),
   (E = '' ->
       L = H;
    (E = 'ENOENT'; E = 'ENOTDIR') ->
       throw(error(existence_error(directory,F),_));
    throw(error(resource_error(io_exception),_))).

/****************************************************************/
/* Directory Access                                             */
/****************************************************************/

/**
 * sys_directory_member(F, L):
 * The predicate succeeds in L with the files of the directory F.
 */
% sys_directory_member(+Atom, -Atom)
sys_directory_member(F, N) :-
   directory_files(F, L),
   member(N, L).

/**
 * sys_ensure_directory(F):
 * The predicate succeeds. As a side effect it ensures a directory F.
 */
% sys_ensure_directory(+Atom)
sys_ensure_directory(F) :-
   file_property(F, type(directory)), !.
sys_ensure_directory(F) :-
   make_directory(F).

/*******************************************************************/
/* Copy Context                                                    */
/*******************************************************************/

/**
 * copy_text(A, B):
 * copy_text(A, B, O):
 * The predicate succeeds. As side effect it copies the
 * file A into the file B. An already existing file B
 * is silently overwritten. The ternary predicate allows
 * specifying copy file options.
 */
% copy_text(+Atom, +Atom)
copy_text(InName, OutName) :-
   copy_text(InName, OutName, []).

% copy_text(+Atom, +Atom, +List)
copy_text(InName, OutName, Opt) :-
   sys_copy_file_opts(Opt, 0, Flags),
   (Flags /\ 1 =:= 0 -> Mode = write; Mode = append),
   sys_copy_file(InName, OutName, Mode, [], []).

/**
 * copy_binary(A, B):
 * copy_binary(A, B, O):
 * The predicate succeeds. As side effect it copies the
 * file A into the file B. An already existing file B
 * is silently overwritten. The ternary predicate allows
 * specifying copy file options.
 */
% copy_binary(+Atom, +Atom)
copy_binary(InName, OutName) :-
   copy_binary(InName, OutName, []).

% copy_binary(+Atom, +Atom, +List)
copy_binary(InName, OutName, Opt) :-
   sys_copy_file_opts(Opt, 0, Flags),
   (Flags /\ 1 =:= 0 -> Mode = write; Mode = append),
   sys_copy_file(InName, OutName, Mode,
      [stop(-1), compress(false), max(8192)], [type(binary)]).

/*******************************************************************/
/* Copy Helpers                                                    */
/*******************************************************************/

% sys_copy_file(+Atom, +Atom, +Atom, +List, +List)
sys_copy_file(InName, OutName, Mode, Opts, Opts2) :-
   setup_call_cleanup(
      open(OutName, Mode, OutStream, Opts2),
      sys_copy_stream(InName, OutStream, Opts, Opts2),
      close(OutStream)).

% sys_copy_stream(+Atom, +Stream, +List, +List)
sys_copy_stream(InName, OutStream, Opts, Opts2) :-
   setup_call_cleanup(
      open(InName, read, InStream, Opts2),
      sys_copy_atoms(InStream, OutStream, Opts),
      close(InStream)).

% sys_copy_atoms(+Stream, +Stream, +List)
sys_copy_atoms(InStream, OutStream, Opts) :-
   sys_enum_atoms(InStream, Line, Opts),
   put_atom(OutStream, Line),
   fail.
sys_copy_atoms(_, _, _).

/**
 * sys_enum_atoms(S, A):
 * sys_enum_atoms(S, A, O):
 * The predicate succeeds in A with the subsequent atoms
 * from the stream S. The terminary predicate allows
 * specifying atom options.
 */
% sys_enum_atoms(+Stream, -Line)
sys_enum_atoms(InStream, Line) :-
   sys_enum_atoms(InStream, Line, []).

% sys_enum_atoms(+Stream, -Line, +List)
sys_enum_atoms(InStream, Line, Opts) :-
   repeat,
   get_atom(InStream, Line, Opts),
   (Line \== '' ->
      true; !, fail).

/****************************************************************/
/* Content Options                                              */
/****************************************************************/

% sys_copy_file_opts(+List, +Integer, -Integer)
sys_copy_file_opts(V, _, _) :- var(V),
   throw(error(instantiation_error,_)).
sys_copy_file_opts([X|L], I, O) :- !,
   sys_copy_file_opt(X, I, H),
   sys_copy_file_opts(L, H, O).
sys_copy_file_opts([], H, H) :- !.
sys_copy_file_opts(L, _, _) :-
   throw(error(type_error(list,L),_)).

% sys_copy_file_opt(+Option, +Triple, -Triple)
sys_copy_file_opt(V, _, _) :- var(V),
   throw(error(instantiation_error,_)).
sys_copy_file_opt(append(B), F, G) :- !,
   sys_opt_boolean(B, 1, F, G).
sys_copy_file_opt(O, _, _) :-
   throw(error(domain_error(copy_option,O),_)).

/*******************************************************************/
/* Copy Meta                                                       */
/*******************************************************************/

/**
 * copy_time(A, B):
 * copy_time(A, B, O):
 * The predicate succeeds. As side effect it copies the last modified
 * date from file A to the last modified date of file B. The ternary
 * predicate allows specifying copy time options.
 */
% copy_time(+Atom, +Atom)
copy_time(InName, OutName) :-
   copy_time(InName, OutName, []).

% copy_time(+Atom, +Atom, +List)
copy_time(InName, OutName, Opt) :-
   sys_copy_time_opts(Opt, 0, Flags),
   sys_file_name_time(InName, _, InTime),
   sys_copy_time(InTime, OutName, Flags).

% sys_copy_time(+Integer, +Atom, +Integer)
sys_copy_time(InTime, OutName, Flags) :- Flags /\ 1 =\= 0,
   sys_file_name_time(OutName, _, OutTime),
   InTime =< OutTime, !.
sys_copy_time(InTime, OutName, _) :-
   set_file_property(OutName, last_modified(InTime)).

/****************************************************************/
/* Meta Options                                                 */
/****************************************************************/

% sys_copy_time_opts(+List, +Integer, -Integer)
sys_copy_time_opts(V, _, _) :- var(V),
   throw(error(instantiation_error,_)).
sys_copy_time_opts([X|L], I, O) :- !,
   sys_copy_time_opt(X, I, H),
   sys_copy_time_opts(L, H, O).
sys_copy_time_opts([], H, H) :- !.
sys_copy_time_opts(L, _, _) :-
   throw(error(type_error(list,L),_)).

% sys_copy_time_opt(+Option, +Triple, -Triple)
sys_copy_time_opt(V, _, _) :- var(V),
   throw(error(instantiation_error,_)).
sys_copy_time_opt(update(B), F, G) :- !,
   sys_opt_boolean(B, 1, F, G).
sys_copy_time_opt(O, _, _) :-
   throw(error(domain_error(bundle_option,O),_)).

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

% strings(+Atom, +Atom, -Atom)
:- multifile(strings/3).
strings('domain_error.copy_option', de, 'Kopieroption erwartet, gefunden ~q.').
strings('domain_error.bundle_option', de, 'Bündeloption erwartet, gefunden ~q.').

strings('existence_error.directory', de, 'Verzeichnis ~q nicht gefunden.').

strings('permission_error.delete.file', de, 'Kann Datei ~q nicht löschen.').
strings('permission_error.remove.directory', de, 'Kann Verzeichnis ~q nicht entfernen.').
strings('permission_error.create.directory', de, 'Kann Verzeichnis ~q nicht erstellen.').

strings('domain_error.copy_option', '', 'Copy option expected, found ~q.').
strings('domain_error.bundle_option', '', 'Bundle option expected, found ~q.').

strings('existence_error.directory', '', 'Directory ~q not found.').

strings('permission_error.delete.file', '', 'Cannot delete file ~q.').
strings('permission_error.remove.directory', '', 'Cannot remove directory ~q.').
strings('permission_error.create.directory', '', 'Cannot create directory ~q.').

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

% os_unlink_sync(F, E)
% defined in foreign(text/oslib)

% os_rmdir_sync(F, E)
% defined in foreign(text/oslib)

% os_mkdir_sync(F, E)
% defined in foreign(text/oslib)

% os_readdir_sync(F, L, E)
% defined in foreign(text/oslib)

% os_prop2_promise(F, M, Q)
% defined in foreign(text/oslib)

:- ensure_loaded(foreign(text/oslib)).