##
# Copyright (c) 2005-2017 Apple Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# DRI: Cyrus Daboo, cdaboo@apple.com
##

"""
PUT/COPY/MOVE common behavior.
"""

__version__ = "0.0"

__all__ = ["storeResource"]

from twisted.python.failure import Failure
from twext.python.filepath import CachingFilePath as FilePath
from twisted.internet.defer import deferredGenerator, maybeDeferred, waitForDeferred

from twext.python.log import Logger
from txweb2 import responsecode
from txweb2.dav.fileop import copy, delete, put
from txweb2.dav.http import ErrorResponse
from txweb2.dav.resource import TwistedGETContentMD5
from txweb2.stream import MD5Stream
from txweb2.http import HTTPError
from txweb2.http_headers import generateContentType
from txweb2.iweb import IResponse
from txweb2.stream import MemoryStream

from txdav.xml import element as davxml
from txdav.xml.base import dav_namespace

log = Logger()


def storeResource(
    request,
    source=None, source_uri=None, data=None,
    destination=None, destination_uri=None,
    deletesource=False,
    depth="0"
):
    """
    Function that does common PUT/COPY/MOVE behaviour.

    @param request:           the L{txweb2.server.Request} for the current HTTP request.
    @param source:            the L{DAVFile} for the source resource to copy from, or None if source data
                              is to be read from the request.
    @param source_uri:        the URI for the source resource.
    @param data:              a C{str} to copy data from instead of the request stream.
    @param destination:       the L{DAVFile} for the destination resource to copy into.
    @param destination_uri:   the URI for the destination resource.
    @param deletesource:      True if the source resource is to be deleted on successful completion, False otherwise.
    @param depth:             a C{str} containing the COPY/MOVE Depth header value.
    @return:                  status response.
    """

    try:
        assert request is not None and destination is not None and destination_uri is not None
        assert (source is None) or (source is not None and source_uri is not None)
        assert not deletesource or (deletesource and source is not None)
    except AssertionError:
        log.error("Invalid arguments to storeResource():")
        log.error("request=%s\n" % (request,))
        log.error("source=%s\n" % (source,))
        log.error("source_uri=%s\n" % (source_uri,))
        log.error("data=%s\n" % (data,))
        log.error("destination=%s\n" % (destination,))
        log.error("destination_uri=%s\n" % (destination_uri,))
        log.error("deletesource=%s\n" % (deletesource,))
        log.error("depth=%s\n" % (depth,))
        raise

    class RollbackState(object):
        """
        This class encapsulates the state needed to rollback the entire PUT/COPY/MOVE
        transaction, leaving the server state the same as it was before the request was
        processed. The DoRollback method will actually execute the rollback operations.
        """

        def __init__(self):
            self.active = True
            self.source_copy = None
            self.destination_copy = None
            self.destination_created = False
            self.source_deleted = False

        def Rollback(self):
            """
            Rollback the server state. Do not allow this to raise another exception. If
            rollback fails then we are going to be left in an awkward state that will need
            to be cleaned up eventually.
            """
            if self.active:
                self.active = False
                log.error("Rollback: rollback")
                try:
                    if self.source_copy and self.source_deleted:
                        self.source_copy.moveTo(source.fp)
                        log.error("Rollback: source restored %s to %s" % (self.source_copy.path, source.fp.path))
                        self.source_copy = None
                        self.source_deleted = False
                    if self.destination_copy:
                        destination.fp.remove()
                        log.error("Rollback: destination restored %s to %s" % (self.destination_copy.path, destination.fp.path))
                        self.destination_copy.moveTo(destination.fp)
                        self.destination_copy = None
                    elif self.destination_created:
                        destination.fp.remove()
                        log.error("Rollback: destination removed %s" % (destination.fp.path,))
                        self.destination_created = False
                except:
                    log.error("Rollback: exception caught and not handled: %s" % Failure())

        def Commit(self):
            """
            Commit the resource changes by wiping the rollback state.
            """
            if self.active:
                log.error("Rollback: commit")
                self.active = False
                if self.source_copy:
                    self.source_copy.remove()
                    log.error("Rollback: removed source backup %s" % (self.source_copy.path,))
                    self.source_copy = None
                if self.destination_copy:
                    self.destination_copy.remove()
                    log.error("Rollback: removed destination backup %s" % (self.destination_copy.path,))
                    self.destination_copy = None
                self.destination_created = False