module Toml = Toml
module Console = Console

let date_from_csv : string -> CalendarLib.Date.t option =
 fun value ->
  let open CalendarLib.Date in
  try Some (Scanf.sscanf value "%d/%d/%d" (fun d m y -> make y m d)) with
  | _ -> (
      (* If the date is a number, try from julian day *)
      match int_of_string_opt value with
      | None -> None
      | Some v -> Some (add (make 1899 12 30) (Period.day v)))

let fold_opt : ('a -> 'b -> 'a option) -> 'a -> 'b -> 'a =
 fun f acc b ->
  match f acc b with
  | None -> acc
  | Some v -> v

let try_opt exp =
  try Some (exp ()) with
  | _ -> None

let repr_date formatter date =
  Format.fprintf formatter "%02d/%02d/%d"
    (CalendarLib.Date.day_of_month date)
    CalendarLib.Date.(int_of_month @@ month date)
    (CalendarLib.Date.year date)

let s_repr_date date =
  Format.sprintf "%02d/%02d/%d"
    (CalendarLib.Date.day_of_month date)
    CalendarLib.Date.(int_of_month @@ month date)
    (CalendarLib.Date.year date)

let repr_opt f channel = function
  | None -> ()
  | Some v -> f channel v

let str_format f =
  let buffer = Buffer.create 16 in
  let formatter = Format.formatter_of_buffer buffer in
  f formatter;
  Format.pp_print_flush formatter ();
  Buffer.contents buffer