from __future__ import with_statement

from json import dumps

import xmlrpclib

from abl.vpath.base import URI


class FakeUsageReporter(object):
    def __init__(self):
        self.events = []
        self.params = []

    def log(self, event, **params):
        self.events.append(event)
        self.params.append(dumps(params))


class FakeTransport(object):
    def __init__(self, mock, session_id=None):
        self.mock = mock
        if session_id is None:
            session_id = "foobar"
        self.session_id = session_id

    def request(self, host, handler, request_body, verbose=False):
        (frame, args, kwargs), methodname = xmlrpclib.loads(request_body)
        # for now, we don't support kwargs!
        assert not kwargs
        res = getattr(self.mock, methodname)(*args)
        if not frame["sid"]:
            frame["sid"] = self.session_id
        return [frame, res]


def create_file(path, content="foo"):
    path.directory().makedirs()
    with (path).open("w") as outf:
        outf.write(content)
    return path


def cleanup_memory_fs():
    base = URI("memory:///")
    horrible_hack_file = base / "__access_guts_through_me__"
    with horrible_hack_file.open("w") as outf:
        outf.mem_file.FILE_LOCKS.clear()

    for fname in base.listdir():
        f = base / fname
        if f.isdir():
            for subname in f.listdir():
                try:
                    (f / subname)._manipulate(unlock=True)
                except:
                    pass
                (f / subname).remove()
        f.remove()
