/* -*- 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 DejaDup.ResticLogger : Object
{
  public static string? from_cache_log(DejaDup.LogObscurer obscurer)
  {
    var contents = read_cachefile();
    if (contents == null)
      return null;

    var result = "";

    var lines = contents.split("\n");
    for (int i = 0; i < lines.length; i++) {
      unowned var line = lines[i];
      var is_stanza = (line.has_prefix("{") && line.has_suffix("}")) ||
                      (line.has_prefix("[") && line.has_suffix("]"));
      if (!is_stanza)
        result += obscurer.replace_freeform_text(line);
      else {
        result += replace_json(obscurer, line);
      }
      result += "\n";
    }

    return result;
  }

  public static string? get_cachefile()
  {
    var cachedir = Environment.get_user_cache_dir();
    if (cachedir == null)
      return null;

    return Path.build_filename(cachedir, Config.PACKAGE, "restic.log");
  }

  static string? read_cachefile()
  {
    try {
      string contents;
      FileUtils.get_contents(get_cachefile(), out contents);
      return contents;
    }
    catch (Error e) {
      return null; // likely not there at all
    }
  }

  static string replace_json(DejaDup.LogObscurer obscurer, string line)
  {
    var parser = new Json.Parser();
    try {
      parser.load_from_data(line);
    } catch (Error e) {
      return obscurer.replace_freeform_text(line);
    }

    var root = parser.get_root();
    replace_node(obscurer, root);
    return Json.to_string(root, false);
  }

  static void replace_node(DejaDup.LogObscurer obscurer, Json.Node node)
  {
    var node_type = node.get_node_type();
    if (node_type == Json.NodeType.OBJECT) {
      node.get_object().foreach_member((obj, name, n) => replace_node(obscurer, n));
    }
    else if (node_type == Json.NodeType.ARRAY) {
      node.get_array().foreach_element((arr, i, n) => replace_node(obscurer, n));
    }
    else if (node_type == Json.NodeType.VALUE) {
      var strval = node.get_string();
      if (strval != null && strval[0] == '/') {
        node.set_string(obscurer.replace_path(strval));
      }
    }
  }
}
