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

using GLib;

public class ConfigAutoBackup : BuilderWidget
{
  public ConfigAutoBackup(Gtk.Builder builder) {
    Object(builder: builder);
  }

  construct {
    var auto_backup = builder.get_object("auto_backup") as Gtk.Switch;
    adopt_widget(auto_backup);

    var settings = DejaDup.get_settings();
    settings.bind(DejaDup.PERIODIC_KEY, auto_backup, "active", SettingsBindFlags.GET);

    auto_backup.state_set.connect(on_state_set);
  }

  static bool on_state_set(Gtk.Switch auto_switch, bool state)
  {
    if (state) {
      Background.request_autostart.begin(auto_switch, (obj, res) => {
        if (Background.request_autostart.end(res)) {
          auto_switch.state = true; // finish state set
          set_periodic(true);
        } else {
          auto_switch.active = false; // flip switch back to unset mode
        }
      });
      return true; // delay setting of state
    }

    set_periodic(false);
    return false;
  }

  static void set_periodic(bool state)
  {
    var settings = DejaDup.get_settings();
    settings.set_boolean(DejaDup.PERIODIC_KEY, state);
  }
}
