/* -*- Mode: Vala; indent-tabs-mode: nil; tab-width: 2 -*-
 *
 * SPDX-License-Identifier: GPL-3.0-or-later
 * SPDX-FileCopyrightText: Michael Terry
 */

using GLib;

[GtkTemplate (ui = "/org/gnome/DejaDup/RecentBackupRow.ui")]
public class RecentBackupRow : Adw.ActionRow
{
  uint timeout_id;

  construct {
    var watcher = DejaDup.BackendWatcher.get_instance();
    watcher.new_backup.connect(update_label);

    update_label();

    // Update the label every hour to lazily catch cross-day boundaries
    timeout_id = Timeout.add_seconds(60 * 60, update_label_timer);
  }

  ~RecentBackupRow()
  {
    Source.remove(timeout_id);
  }

  bool is_same_day(DateTime one, DateTime two)
  {
    var one_local = one.to_local();
    var two_local = two.to_local();

    int ny, nm, nd, dy, dm, dd;
    one_local.get_ymd(out ny, out nm, out nd);
    two_local.get_ymd(out dy, out dm, out dd);

    return (ny == dy && nm == dm && nd == dd);
  }

  string pretty_last_name(DateTime date)
  {
    var now = DejaDup.now();

    // A last date in the future doesn't make any sense.
    // Pretending it happened today doesn't make any more sense, but at
    // least is intelligible.
    if (now.compare(date) < 0)
      date = now;

    // Check for some really simple/common friendly names
    if (is_same_day(date, now))
      return _("Today");
    else if (is_same_day(date, now.add_days(-1)))
      return _("Yesterday");
    else {
      now = new DateTime.utc(now.get_year(),
                             now.get_month(),
                             now.get_day_of_month(),
                             0, 0, 0.0);
      var diff = (int)(now.difference(date) / TimeSpan.DAY + 1);
      // Translators: sentence case
      return dngettext(Config.GETTEXT_PACKAGE,
                       "%d day ago",
                       "%d days ago", diff).printf(diff);
    }
  }

  bool update_label_timer()
  {
    update_label();
    return Source.CONTINUE;
  }

  void update_label()
  {
    var settings = DejaDup.get_settings();
    var last = settings.get_string(DejaDup.LAST_BACKUP_KEY);
    var last_time = new DateTime.from_iso8601(last, new TimeZone.utc());
    if (last_time == null)
      // Translators: this is used like "Most Recent Backup: None"
      subtitle = C_("backups", "None");
    else
      subtitle = pretty_last_name(last_time);
  }
}
