open Accountdbase
open Account

let fixme_rexp = Str.regexp "^.*FIXME.*$"

let print_group channel group_name accts =
  let sorted_accts = List.sort (fun acct1 -> fun acct2 ->
                                  compare (Account.full_name acct1)
                                          (Account.full_name acct2)) accts
  in
    output_string channel "<tr><td colspan=\"2\"><b>";
    output_string channel group_name;
    output_string channel "</b></td></tr>";
    List.iter (fun acct ->
      let fixme_present =
        Account.fold_txns (fun flag -> fun txn ->
  	                   if flag
  			   then true
  			   else
  			     Str.string_match fixme_rexp txn.description 0)
                          false acct
      in
        output_string channel "<tr><td class=\"groupsummary\"><a href=\"bill-";
        output_string channel (Account.short_name acct);
        output_string channel ".html\">";
        output_string channel (Account.full_name acct);
        output_string channel "</a>";
	(if fixme_present then
	   output_string channel "&nbsp;&nbsp;<i>Needs attention.</i>");
	output_string channel "</td>";
        let must_be_zero =
          try Account.lookup_boolean_variable "must_be_zero" acct
  	with Not_found -> false
        in
        let total = Account.total acct in
          if must_be_zero then
  	begin
            if Sumofmoney.is_zero (Sumofmoney.default_to_normal total) then
             output_string channel "<td class=\"grandtotalp\">OK"
  	  else
             output_string channel "<td class=\"grandtotaln\">Not correct"
  	end
  	else
  	begin
            (if Sumofmoney.non_negative_default total then
              output_string channel "<td class=\"grandtotalp\">"
            else if Sumofmoney.very_negative_default total then
              output_string channel "<td class=\"grandtotaln\">"
            else
              output_string channel "<td class=\"grandtotalm\">");
            output_string channel (Sumofmoney.to_string_default total)
          end;
          output_string channel "</td></tr>"
    ) sorted_accts;
    output_string channel "<tr><td></td><td></td></tr>"

let emit () =
  Misc.verbose "Reading title file.";
  let channel = Misc.open_config_file "title" in
  try
    let title = input_line channel in
    Misc.verbose "Preparing to emit the group summary sheet.";
    let groups = Accountdbase.group "group" in
    let html_channel = Htmlout.create_page "index"
                       title in
      output_string html_channel "<table width=\"100%\">";
      AccountsMap.iter (print_group html_channel) groups;
      output_string html_channel "</table>";
      Htmlout.finish_page html_channel
  with End_of_file ->
    Misc.fail "Could not read title (check title file has contents)"

