# Copyright (C) 2013 Red Hat, Inc.  All rights reserved.
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
#
# Authors: Jan Safranek <jsafrane@redhat.com>
# -*- coding: utf-8 -*-
"""
Module for FormatProvider.

LMI_MDRAIDFormatProvider
------------------------

.. autoclass:: LMI_MDRAIDFormatProvider
    :members:

"""

from lmi.storage.FormatProvider import FormatProvider
import blivet.formats.mdraid
import lmi.providers.cmpi_logging as cmpi_logging
from lmi.storage.util import storage

class LMI_MDRAIDFormatProvider(FormatProvider):
    """
        Provider of MD RAID format on a device.
    """
    @cmpi_logging.trace_method
    def __init__(self, *args, **kwargs):
        super(LMI_MDRAIDFormatProvider, self).__init__(
                "LMI_MDRAIDFormat",
                "mdmember",
                *args, **kwargs)

    @cmpi_logging.trace_method
    def provides_format(self, device, fmt):
        if  isinstance(fmt, blivet.formats.mdraid.MDRaidMember):
            return True
        return False

    @cmpi_logging.trace_method
    def get_format_id(self, device, fmt):
        """
            Return LMI_DataFormat.Name. The name should be unique and stable
            across reboots or reconfigurations.

            This is workaround for MDRaidMember reporting wrong UUID, see
            https://bugzilla.redhat.com/show_bug.cgi?id=1070095
        """
        # TODO: remove this method when 1070095 is fixed
        return "DEVICE=" + storage.get_persistent_name(device)

    @cmpi_logging.trace_method
    def get_instance(self, env, model, fmt=None):
        """
            Get instance.
        """
        model = super(LMI_MDRAIDFormatProvider, self).get_instance(
                env, model, fmt)
        if not fmt:
            (device, fmt) = self.get_format_for_id(model['Name'])
        model['MDUUID'] = fmt.mdUuid
        return model
