
import tempfile

from bzrlib import (
    bzrdir,
    errors,
    revision
    )
from bzrlib.bundle.serializer import write_bundle


class SmartServerResponse(object):
    """Response generated by SmartServerRequestHandler."""

    def __init__(self, args, body=None):
        self.args = args
        self.body = body

# XXX: TODO: Create a SmartServerRequestHandler which will take the responsibility
# for delivering the data for a request. This could be done with as the
# StreamServer, though that would create conflation between request and response
# which may be undesirable.

class SmartServerRequestHandler(object):
    """Protocol logic for smart server.
    
    This doesn't handle serialization at all, it just processes requests and
    creates responses.
    """

    # IMPORTANT FOR IMPLEMENTORS: It is important that SmartServerRequestHandler
    # not contain encoding or decoding logic to allow the wire protocol to vary
    # from the object protocol: we will want to tweak the wire protocol separate
    # from the object model, and ideally we will be able to do that without
    # having a SmartServerRequestHandler subclass for each wire protocol, rather
    # just a Protocol subclass.

    # TODO: Better way of representing the body for commands that take it,
    # and allow it to be streamed into the server.
    
    def __init__(self, backing_transport):
        self._backing_transport = backing_transport
        self._converted_command = False
        self.finished_reading = False
        self._body_bytes = ''
        self.response = None

    def accept_body(self, bytes):
        """Accept body data.

        This should be overriden for each command that desired body data to
        handle the right format of that data. I.e. plain bytes, a bundle etc.

        The deserialisation into that format should be done in the Protocol
        object. Set self.desired_body_format to the format your method will
        handle.
        """
        # default fallback is to accumulate bytes.
        self._body_bytes += bytes
        
    def _end_of_body_handler(self):
        """An unimplemented end of body handler."""
        raise NotImplementedError(self._end_of_body_handler)
        
    def do_hello(self):
        """Answer a version request with my version."""
        return SmartServerResponse(('ok', '1'))

    def do_has(self, relpath):
        r = self._backing_transport.has(relpath) and 'yes' or 'no'
        return SmartServerResponse((r,))

    def do_get(self, relpath):
        backing_bytes = self._backing_transport.get_bytes(relpath)
        return SmartServerResponse(('ok',), backing_bytes)

    def _deserialise_optional_mode(self, mode):
        # XXX: FIXME this should be on the protocol object.
        if mode == '':
            return None
        else:
            return int(mode)

    def do_append(self, relpath, mode):
        self._converted_command = True
        self._relpath = relpath
        self._mode = self._deserialise_optional_mode(mode)
        self._end_of_body_handler = self._handle_do_append_end
    
    def _handle_do_append_end(self):
        old_length = self._backing_transport.append_bytes(
            self._relpath, self._body_bytes, self._mode)
        self.response = SmartServerResponse(('appended', '%d' % old_length))

    def do_delete(self, relpath):
        self._backing_transport.delete(relpath)

    def do_iter_files_recursive(self, relpath):
        transport = self._backing_transport.clone(relpath)
        filenames = transport.iter_files_recursive()
        return SmartServerResponse(('names',) + tuple(filenames))

    def do_list_dir(self, relpath):
        filenames = self._backing_transport.list_dir(relpath)
        return SmartServerResponse(('names',) + tuple(filenames))

    def do_mkdir(self, relpath, mode):
        self._backing_transport.mkdir(relpath,
                                      self._deserialise_optional_mode(mode))

    def do_move(self, rel_from, rel_to):
        self._backing_transport.move(rel_from, rel_to)

    def do_put(self, relpath, mode):
        self._converted_command = True
        self._relpath = relpath
        self._mode = self._deserialise_optional_mode(mode)
        self._end_of_body_handler = self._handle_do_put

    def _handle_do_put(self):
        self._backing_transport.put_bytes(self._relpath,
                self._body_bytes, self._mode)
        self.response = SmartServerResponse(('ok',))

    def _deserialise_offsets(self, text):
        # XXX: FIXME this should be on the protocol object.
        offsets = []
        for line in text.split('\n'):
            if not line:
                continue
            start, length = line.split(',')
            offsets.append((int(start), int(length)))
        return offsets

    def do_put_non_atomic(self, relpath, mode, create_parent, dir_mode):
        self._converted_command = True
        self._end_of_body_handler = self._handle_put_non_atomic
        self._relpath = relpath
        self._dir_mode = self._deserialise_optional_mode(dir_mode)
        self._mode = self._deserialise_optional_mode(mode)
        # a boolean would be nicer XXX
        self._create_parent = (create_parent == 'T')

    def _handle_put_non_atomic(self):
        self._backing_transport.put_bytes_non_atomic(self._relpath,
                self._body_bytes,
                mode=self._mode,
                create_parent_dir=self._create_parent,
                dir_mode=self._dir_mode)
        self.response = SmartServerResponse(('ok',))

    def do_readv(self, relpath):
        self._converted_command = True
        self._end_of_body_handler = self._handle_readv_offsets
        self._relpath = relpath

    def end_of_body(self):
        """No more body data will be received."""
        self._run_handler_code(self._end_of_body_handler, (), {})
        # cannot read after this.
        self.finished_reading = True

    def _handle_readv_offsets(self):
        """accept offsets for a readv request."""
        offsets = self._deserialise_offsets(self._body_bytes)
        backing_bytes = ''.join(bytes for offset, bytes in
            self._backing_transport.readv(self._relpath, offsets))
        self.response = SmartServerResponse(('readv',), backing_bytes)
        
    def do_rename(self, rel_from, rel_to):
        self._backing_transport.rename(rel_from, rel_to)

    def do_rmdir(self, relpath):
        self._backing_transport.rmdir(relpath)

    def do_stat(self, relpath):
        stat = self._backing_transport.stat(relpath)
        return SmartServerResponse(('stat', str(stat.st_size), oct(stat.st_mode)))
        
    def do_get_bundle(self, path, revision_id):
        # open transport relative to our base
        t = self._backing_transport.clone(path)
        control, extra_path = bzrdir.BzrDir.open_containing_from_transport(t)
        repo = control.open_repository()
        tmpf = tempfile.TemporaryFile()
        base_revision = revision.NULL_REVISION
        write_bundle(repo, revision_id, base_revision, tmpf)
        tmpf.seek(0)
        return SmartServerResponse((), tmpf.read())

    def dispatch_command(self, cmd, args):
        """Deprecated compatibility method.""" # XXX XXX
        func = getattr(self, 'do_' + cmd, None)
        if func is None:
            raise errors.SmartProtocolError("bad request %r" % (cmd,))
        self._run_handler_code(func, args, {})

    def _run_handler_code(self, callable, args, kwargs):
        """Run some handler specific code 'callable'.

        If a result is returned, it is considered to be the commands response,
        and finished_reading is set true, and its assigned to self.response.

        Any exceptions caught are translated and a response object created
        from them.
        """
        result = self._call_converting_errors(callable, args, kwargs)
        if result is not None:
            self.response = result
            self.finished_reading = True
        # handle unconverted commands
        if not self._converted_command:
            self.finished_reading = True
            if result is None:
                self.response = SmartServerResponse(('ok',))

    def _call_converting_errors(self, callable, args, kwargs):
        """Call callable converting errors to Response objects."""
        try:
            return callable(*args, **kwargs)
        except errors.NoSuchFile, e:
            return SmartServerResponse(('NoSuchFile', e.path))
        except errors.FileExists, e:
            return SmartServerResponse(('FileExists', e.path))
        except errors.DirectoryNotEmpty, e:
            return SmartServerResponse(('DirectoryNotEmpty', e.path))
        except errors.ShortReadvError, e:
            return SmartServerResponse(('ShortReadvError',
                e.path, str(e.offset), str(e.length), str(e.actual)))
        except UnicodeError, e:
            # If it is a DecodeError, than most likely we are starting
            # with a plain string
            str_or_unicode = e.object
            if isinstance(str_or_unicode, unicode):
                # XXX: UTF-8 might have \x01 (our seperator byte) in it.  We
                # should escape it somehow.
                val = 'u:' + str_or_unicode.encode('utf-8')
            else:
                val = 's:' + str_or_unicode.encode('base64')
            # This handles UnicodeEncodeError or UnicodeDecodeError
            return SmartServerResponse((e.__class__.__name__,
                    e.encoding, val, str(e.start), str(e.end), e.reason))
        except errors.TransportNotPossible, e:
            if e.msg == "readonly transport":
                return SmartServerResponse(('ReadOnlyError', ))
            else:
                raise


