# vim: tabstop=4 shiftwidth=4 softtabstop=4

# Copyright 2013 Cloudbase Solutions Srl
# 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.

"""
Management class for migration / resize operations.
"""
import os

from nova.openstack.common import excutils
from nova.openstack.common import log as logging
from nova.virt.hyperv import hostutils
from nova.virt.hyperv import imagecache
from nova.virt.hyperv import pathutils
from nova.virt.hyperv import vhdutils
from nova.virt.hyperv import vmops
from nova.virt.hyperv import vmutils
from nova.virt.hyperv import volumeops

LOG = logging.getLogger(__name__)


class MigrationOps(object):
    def __init__(self):
        self._hostutils = hostutils.HostUtils()
        self._vmutils = vmutils.VMUtils()
        self._vhdutils = vhdutils.VHDUtils()
        self._pathutils = pathutils.PathUtils()
        self._volumeops = volumeops.VolumeOps()
        self._vmops = vmops.VMOps()
        self._imagecache = imagecache.ImageCache()

    def _migrate_disk_files(self, instance_name, disk_files, dest):
        same_host = False
        if dest in self._hostutils.get_local_ips():
            same_host = True
            LOG.debug(_("Migration target is the source host"))
        else:
            LOG.debug(_("Migration target host: %s") % dest)

        instance_path = self._pathutils.get_instance_dir(instance_name)
        revert_path = self._pathutils.get_instance_migr_revert_dir(
            instance_name, remove_dir=True)
        dest_path = None

        try:
            if same_host:
                # Since source and target are the same, we copy the files to
                # a temporary location before moving them into place
                dest_path = '%s_tmp' % instance_path
                if self._pathutils.exists(dest_path):
                    self._pathutils.rmtree(dest_path)
                self._pathutils.makedirs(dest_path)
            else:
                dest_path = self._pathutils.get_instance_dir(
                    instance_name, dest, remove_dir=True)
            for disk_file in disk_files:
                # Skip the config drive as the instance is already configured
                if os.path.basename(disk_file).lower() != 'configdrive.vhd':