from __future__ import with_statement

import os.path
import threading
import string
import re
import random
import shutil
import time
from subprocess import Popen, PIPE
from riak.util import deep_merge

try:
  bytes
except NameError:
  bytes = str

class Atom(object):
    def __init__(self, s):
        self.str = s

    def __str__(self):
        return str(self.str)

    def __repr__(self):
        return repr(self.str)

    def __eq__(self, other):
        return self.str == other

    def __cmp__(self, other):
        return cmp(self.str, other)

def erlang_config(hash, depth=1):
    def printable(item):
        k, v = item
        if isinstance(v, str):
            p = '"%s"' % v
        elif isinstance(v, dict):
            p = erlang_config(v, depth + 1)
        elif isinstance(v, bool):
            p = ("%s" % v).lower()
        else:
            p = "%s" % v

        return "{%s, %s}" % (k, p)

    padding = '    ' * depth
    parent_padding = '    ' * (depth-1)
    values = (",\n%s" % padding).join(map(printable, hash.items()))
    return "[\n%s%s\n%s]" % (padding, values, parent_padding)


class TestServer:
    VM_ARGS_DEFAULTS = {
        "-name": "riaktest%d@127.0.0.1" % random.randint(0, 100000),
        "-setcookie": "%d_%d" % (random.randint(0, 100000), random.randint(0, 100000)),
        "+K": "true",
        "+A": 64,
        "-smp": "enable",
        "-env ERL_MAX_PORTS": 4096,
        "-env ERL_FULLSWEEP_AFTER": 10,
        "-pa": os.path.abspath(os.path.join(os.path.dirname(__file__), "erl_src"))
    }

    APP_CONFIG_DEFAULTS = {
      "riak_core": {
          "web_ip": "127.0.0.1",
          "web_port": 9000,
          "handoff_port": 9001,
          "ring_creation_size": 64
      },
      "riak_kv": {
          "storage_backend": Atom("riak_kv_test_backend"),
          "pb_ip": "127.0.0.1",
          "pb_port": 9002,
          "js_vm_count": 8,
          "js_max_vm_mem": 8,
          "js_thread_stack": 16,
          "riak_kv_stat": True,
          "map_cache_size": 0,
          "vnode_cache_entries": 0
      },
      "riak_search": {
          "enabled": True,
          "search_backend": Atom("riak_search_test_backend")
      },
      "luwak": {