var toml = use('toml')

function deep_equal(a, b) {
  var keys_a = null
  var keys_b = null
  var i = 0
  if (a == b) return true
  if (is_null(a) || is_null(b)) return false
  if ((is_number(a) && !is_number(b)) || (is_text(a) && !is_text(b)) || (is_object(a) && !is_object(b)) || (is_array(a) && !is_array(b)) || (is_blob(a) && !is_blob(b)) || (is_function(a) && !is_function(b)) || (is_logical(a) && !is_logical(b))) return false

  if (is_object(a)) {
    keys_a = array(a)
    keys_b = array(b)
    if (length(keys_a) != length(keys_b)) return false

    for (i = 0; i < length(keys_a); i++) {
      if (!deep_equal(a[keys_a[i]], b[keys_a[i]])) return false
    }
    return true
  }

  return false
}

function test_roundtrip(obj, name) {
  var encoded = toml.encode(obj)
  var decoded = toml.decode(encoded)
  if (!deep_equal(obj, decoded)) {
    log.console(name + " - Original:", obj)
    log.console(name + " - Round-trip:", decoded)
    disrupt
  }
}

return {
  test_basic_string: function() {
    var obj = { string_value: "hello world" }
    test_roundtrip(obj, "basic_string")
  },

  test_basic_number: function() {
    var obj = { number_value: 42 }
    test_roundtrip(obj, "basic_number")
  },

  test_basic_float: function() {
    var obj = { float_value: 3.14 }
    test_roundtrip(obj, "basic_float")
  },

  test_basic_bool: function() {
    var obj = { bool_true: true, bool_false: false }
    test_roundtrip(obj, "basic_bool")
  },

  test_basic_array: function() {
    var obj = { array_mixed: ["string", 123, true, false] }
    test_roundtrip(obj, "basic_array")
  },

  test_nested_objects: function() {
    var obj = {
      name: "Test Config",
      version: 1.0,
      database: {
        host: "localhost",
        port: 5432,
        credentials: {
          username: "admin",
          password: "secret123"
        }
      }
    }
    test_roundtrip(obj, "nested_objects")
  },

  test_multiple_nested_sections: function() {
    var obj = {
      servers: {
        alpha: {
          ip: "192.168.1.1",
          port: 8080
        },
        beta: {
          ip: "192.168.1.2",
          port: 8081
        }
      },
      features: ["auth", "api", "websocket"]
    }
    test_roundtrip(obj, "multiple_nested_sections")
  },

  test_empty_string: function() {
    var obj = { empty_string: "" }
    test_roundtrip(obj, "empty_string")
  },

  test_string_with_quotes: function() {
    var obj = { string_with_quotes: 'She said "Hello"' }
    test_roundtrip(obj, "string_with_quotes")
  },

  test_empty_array: function() {
    var obj = { empty_array: [] }
    test_roundtrip(obj, "empty_array")
  },

  test_single_element_array: function() {
    var obj = { single_array: [42] }
    test_roundtrip(obj, "single_element_array")
  },

  test_nested_empty_section: function() {
    var obj = { nested_empty: { section: {} } }
    test_roundtrip(obj, "nested_empty_section")
  }
}
