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

# Copyright 2012 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Copyright 2012 Nebula, Inc.
#
#    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 _  # noqa

from horizon import exceptions
from horizon import forms
from horizon import workflows

from openstack_dashboard.dashboards.admin.models import ResourceRates

from openstack_dashboard import api


class CreateRateInfoAction(workflows.Action):
    TYPE_LIST = (
                 ('', ''),
                 ('flavor.vcpus', 'Virtual CPU'),
                 ('root_gb', 'Root Disk'),
                 ('flavor.ram', 'Memory'),
                 ('volume.size', 'Volume'),
                 ('ip.floating', 'Public IP'),
                 )
    type = forms.ChoiceField(label=_("Resource Types"), choices=TYPE_LIST)
    rate = forms.FloatField(label=_("Resource rate in dollar currency"))

    class Meta:
        name = _("Rate Info")
        help_text = _("From here you can create a new "
                      "resource rates to organize project billings.")
        

    def clean(self):
        cleaned_data = super(CreateRateInfoAction, self).clean()
        type = cleaned_data.get('type')

        try:
            rates = ResourceRates.objects.filter(type=type)
        except Exception:
            msg = _('Unable to get Resource Rate list')
            exceptions.check_message(["Connection", "refused"], msg)
            raise
        
        if rates:
            raise forms.ValidationError(
                _('The resource name "%s" is already has assigned rates!')
                % type )
        return cleaned_data


class CreateRateInfo(workflows.Step):
    action_class = CreateRateInfoAction
    contributes = ("type",
                   "rate"
                   )


class CreateResourceRate(workflows.Workflow):
    slug = "create_resource_rate"
    name = _("Create Resource Rate")
    finalize_button_name = _("Create")
    success_message = _('Created new rate "%s".')
    failure_message = _('Unable to create rate "%s".')
    success_url = "horizon:admin:resource_rates:index"
    default_steps = (CreateRateInfo,
                     )

    def format_status_message(self, message):
        return message % self.context['type']

    def handle(self, request, data):
        try:
            rate = ResourceRates(
                                 type=data['type'],
                                 rate=data['rate']
                                 )
            rate.save()
        except Exception:
            exceptions.handle(request, _('Unable to create resource rate.'))
            return False

        return True
    
class UpdateRateInfoAction(CreateRateInfoAction):
    id = forms.CharField(widget=forms.widgets.HiddenInput)
    type = forms.CharField(widget=forms.widgets.HiddenInput)
    class Meta:
        name = _("Resource Rate Info")
        slug = 'update_info'
        help_text = _("From here you can edit the resource rate and details.")

    def clean(self):
        cleaned_data = super(CreateRateInfoAction, self).clean()
        return cleaned_data



class UpdateRateInfo(workflows.Step):
    action_class = UpdateRateInfoAction
    depends_on = ("id",)
    contributes = ("type",
                   "rate")


class UpdateRate(workflows.Workflow):
    slug = "update_resource_rate"
    name = _("Edit Resource Rate")
    finalize_button_name = _("Update")
    success_message = _('Modified resource rate "%s".')
    failure_message = _('Unable to modify resource rate for "%s".')
    success_url = "horizon:admin:resource_rates:index"
    default_steps = (UpdateRateInfo,
                     )

    def format_status_message(self, message):
        return message % self.context['type']

    def handle(self, request, data):
        id = data["id"]

        # Update flavor information
        try:
            rate = ResourceRates.objects.get(id=id)
            rate.type = data['type']
            rate.rate = data['rate']
            rate.save()
        except Exception:
            exceptions.handle(request, ignore=True)
            return False
        return True

    