from django.db.models import Model, ForeignKey, CharField, DateTimeField, BooleanField
from django.conf import settings
from django.utils import timezone
from vm.models import Lease
from django.utils.translation import ugettext_lazy as _
from datetime import timedelta


class VmLease(Model):
    lease = ForeignKey(Lease, help_text=_("Preferred expiration periods."),
                       verbose_name=_("Lease"))
    os_server_id = CharField(blank=False, max_length=100, unique=True)
    time_of_suspend = DateTimeField(blank=True, default=None, null=True,
                                    verbose_name=_('time of suspend'),
                                    help_text=_("Proposed time of automatic "
                                                "suspension."))
    time_of_delete = DateTimeField(blank=True, default=None, null=True,
                                   verbose_name=_('time of delete'),
                                   help_text=_("Proposed time of automatic "
                                               "deletion."))
    suspend_done = BooleanField(blank=False, default=False)

    def get_renew_times(self, lease=None):
        """Returns new suspend and delete times if renew would be called.
        """
        if lease is None:
            lease = self.lease
        return (
            timezone.now() + lease.suspend_interval,
            timezone.now() + lease.delete_interval)

    def clean(self, *args, **kwargs):
        self.time_of_suspend, self.time_of_delete = self.get_renew_times()
        self.suspend_done = False
        super(VmLease, self).clean(*args, **kwargs)
        return self

    def is_suspend_expiring(self, threshold=0.1):
        limit = timezone.now() + timedelta(seconds=(
                threshold * self.lease.suspend_interval.total_seconds()))
        return limit > self.time_of_suspend

    def is_delete_expiring(self, threshold=0.1):
        limit = timezone.now() + timedelta(seconds=(
                threshold * self.lease.delete_interval.total_seconds()))
        return limit > self.time_of_delete

    @classmethod
    def get_or_create_lease(cls, server_id):
        try:
            return VmLease.objects.get(os_server_id=server_id)
        except VmLease.DoesNotExist:
            lease = VmLease(
                os_server_id=server_id,
                lease=Lease.objects.get(name=settings.DEFAULT_LEASE_NAME)
            )
            lease.clean()
            lease.save()
            return lease
