open Account
open Unix

let read_headers_from_channel short_name channel =
  Misc.verbose ("Reading headers from virtual account file for " ^ short_name);
  let name =
  begin
    try
      input_line channel
    with End_of_file ->
      Misc.fail (
        "Couldn't read first line (account name) from virtual account with short name `"
        ^ short_name ^ "'")
  end
  in
    (name, Variables.read_variables channel)

let load_vaccount_file short_name channel =
  let name, vars = read_headers_from_channel short_name channel in
  let acct = Account.create_virtual short_name name vars in
  let _ = Accountdbase.add_account short_name acct in
  let rec f () =
    let context = "whilst reading virtual account file `" ^ short_name ^ "'" in
    try
      let line = input_line channel in
      let name, negate =
        if String.length line > 0 && String.get line 0 = '-'
        then (String.sub line 1 ((String.length line) - 1)), true
        else line, false
      in
      let acct = Accountdbase.lookup_account name context in
      let total = Sumofmoney.default_to_normal (Account.total acct) in
      let tm = Unix.localtime (Unix.time ()) in
      let total_str = if negate then "Negated total" else "Total" in
      let txn = { year = tm.tm_year + 1900;
                  month = tm.tm_mon + 1;
		  day = tm.tm_mday;
		  amount = if not negate then total
                           else Sumofmoney.negate total;
		  creditor = "phantom";
		  description = total_str ^ " of account " ^
		                (Account.full_name acct);
                  automatically_added = true;
                  linked = false;
		  do_not_symmetrise = true }
      in
        Accountdbase.add_txn short_name txn context;
	f ()
    with End_of_file -> ()
  in
    f ()

let process () =
  Misc.verbose "Processing virtual accounts.";
  Misc.iter_files "vaccounts" load_vaccount_file;
  Misc.verbose "Processing of virtual accounts done."

let process_late () =
  Misc.verbose "Processing late virtual accounts.";
  Misc.iter_files "vaccounts_late" load_vaccount_file;
  Misc.verbose "Processing of late virtual accounts done."

