/* -*- 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/RestoreTargetDialog.ui")]
class RestoreTargetDialog : ActionDialog
{
  public string restore_location {get; private set;}

  public RestoreTargetDialog(DejaDup.FileTree tree, List<File> restore_files)
  {
    Object();
    this.tree = tree;
    this.restore_files = restore_files.copy_deep((CopyFunc)Object.ref);
    update_responses();
  }

  [GtkChild]
  unowned Adw.ActionRow orig_row;
  [GtkChild]
  unowned Adw.ActionRow folder_row;
  [GtkChild]
  unowned Gtk.CheckButton folder_radio;
  [GtkChild]
  unowned Adw.EntryRow folder_entry;
  [GtkChild]
  unowned FolderChooserButton open_button;
  [GtkChild]
  unowned RestoreTargetWarningButton orig_warning;
  [GtkChild]
  unowned RestoreTargetWarningButton folder_warning;

  DejaDup.FileTree tree;
  List<File> restore_files;

  [GtkCallback]
  void handle_file_selected()
  {
    folder_entry.text = open_button.path;
  }

  [GtkCallback]
  void update_responses()
  {
    orig_warning.visible = false;
    orig_row.remove_css_class("error");
    folder_warning.visible = false;
    folder_row.remove_css_class("error");
    folder_entry.remove_css_class("error");

    if (folder_radio.active && folder_entry.text == "") {
      accept_enabled = false;
      return;
    }

    restore_location = "/"; // original locations
    if (folder_radio.active)
      restore_location = DejaDup.resolve_user_dir(folder_entry.text);

    var label = "";

    // Check that we can restore all the selected files into the target.
    var bad_files = RestoreFileTester.get_bad_paths(restore_location, tree, null, restore_files);
    if (bad_files.length() > 0) {
      bad_files.sort(strcmp);
      bad_files.@foreach((file) => {
        if (label != "")
          label += "\n";
        label += file;
      });

      if (folder_radio.active) {
        folder_warning.label = label;
        folder_warning.visible = true;
        folder_row.add_css_class("error");
        folder_entry.add_css_class("error");
      } else {
        orig_warning.label = label;
        orig_warning.visible = true;
        orig_row.add_css_class("error");
      }
    }

    accept_enabled = bad_files.length() == 0;
  }
}
