#    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.

from django.utils.translation import ugettext_lazy as _

from horizon_lib import exceptions
from horizon_lib import forms
from horizon_lib import workflows

from openstack_horizon import api
from openstack_horizon.dashboards.admin.aggregates import constants


class SetAggregateInfoAction(workflows.Action):
    name = forms.CharField(label=_("Name"),
                           max_length=255)

    availability_zone = forms.CharField(label=_("Availability Zone"),
                                        max_length=255)

    class Meta:
        name = _("Host Aggregate Information")
        help_text = _("Host aggregates divide an availability zone into "
                      "logical units by grouping together hosts. Create a "
                      "host aggregate then select the hosts contained in it.")
        slug = "set_aggregate_info"

    def clean(self):
        cleaned_data = super(SetAggregateInfoAction, self).clean()
        name = cleaned_data.get('name')

        try:
            aggregates = api.nova.aggregate_details_list(self.request)
        except Exception:
            msg = _('Unable to get host aggregate list')
            exceptions.check_message(["Connection", "refused"], msg)
            raise
        if aggregates is not None:
            for aggregate in aggregates:
                if aggregate.name.lower() == name.lower():
                    raise forms.ValidationError(
                        _('The name "%s" is already used by '
                          'another host aggregate.')
                        % name
                    )
        return cleaned_data


class SetAggregateInfoStep(workflows.Step):
    action_class = SetAggregateInfoAction
    contributes = ("availability_zone",
                   "name")


class AddHostsToAggregateAction(workflows.MembershipAction):
    def __init__(self, request, *args, **kwargs):
        super(AddHostsToAggregateAction, self).__init__(request,
                                                        *args,
                                                        **kwargs)
        err_msg = _('Unable to get the available hosts')

        default_role_field_name = self.get_default_role_field_name()
        self.fields[default_role_field_name] = forms.CharField(required=False)
        self.fields[default_role_field_name].initial = 'member'

        field_name = self.get_member_field_name('member')
        self.fields[field_name] = forms.MultipleChoiceField(required=False)

        hosts = []
        try:
            hosts = api.nova.host_list(request)
        except Exception:
            exceptions.handle(request, err_msg)

        host_names = []
        for host in hosts:
            if host.host_name not in host_names and host.service == u'compute':
                host_names.append(host.host_name)
        host_names.sort()

        self.fields[field_name].choices = \
            [(host_name, host_name) for host_name in host_names]

    class Meta:
        name = _("Manage Hosts within Aggregate")
        slug = "add_host_to_aggregate"


class ManageAggregateHostsAction(workflows.MembershipAction):
    def __init__(self, request, *args, **kwargs):
        super(ManageAggregateHostsAction, self).__init__(request,
                                                         *args,
                                                         **kwargs)
        err_msg = _('Unable to get the available hosts')

        default_role_field_name = self.get_default_role_field_name()
        self.fields[default_role_field_name] = forms.CharField(required=False)
        self.fields[default_role_field_name].initial = 'member'

        field_name = self.get_member_field_name('member')
        self.fields[field_name] = forms.MultipleChoiceField(required=False)

        aggregate_id = self.initial['id']
        aggregate = api.nova.aggregate_get(request, aggregate_id)
        current_aggregate_hosts = aggregate.hosts

        hosts = []
        try:
            hosts = api.nova.host_list(request)
        except Exception:
            exceptions.handle(request, err_msg)

        host_names = []
        for host in hosts:
            if host.host_name not in host_names and host.service == u'compute':
                host_names.append(host.host_name)
        host_names.sort()

        self.fields[field_name].choices = \
            [(host_name, host_name) for host_name in host_names]

        self.fields[field_name].initial = current_aggregate_hosts

    class Meta:
        name = _("Manage Hosts within Aggregate")


class AddHostsToAggregateStep(workflows.UpdateMembersStep):