import logging
import os

from django.utils.translation import ugettext_lazy as _

from dojango import forms

from freenasUI.common.forms import Form, ModelForm
from freenasUI.middleware.notifier import notifier
from freenasUI.storage.models import Volume

from . import models

log = logging.getLogger('failover.forms')


class CARPForm(ModelForm):

    class Meta:
        model = models.CARP
        exclude = (
            'carp_interface',
        )

    def __init__(self, *args, **kwargs):
        super(CARPForm, self).__init__(*args, **kwargs)
        if not self.instance.id:
            used = [
                v[0]
                for v in models.CARP.objects.order_by(
                    'carp_number'
                ).values_list('carp_number')
            ]
            for i in range(len(used) + 2):
                if i not in used:
                    break
            self.fields['carp_number'].initial = i
        else:
            if self.instance.carp_number in (1, 2):
                self.fields['carp_critical'].widget.attrs['disabled'] = (
                    'disabled'
                )
                self.fields['carp_group'].widget.attrs['disabled'] = (
                    'disabled'
                )
        self.fields['carp_critical'].widget.attrs['onChange'] = (
            'carpCritical(this);'
        )
        self.fields['carp_number'].widget.attrs['onChange'] = (
            'carpCritical(this);'
        )
        if (
            self.instance.id and not self.instance.carp_critical
        ) or not self.instance.id:
            self.fields['carp_group'].widget.attrs['disabled'] = (
                'disabled'
            )

    def clean_carp_vhid(self):
        val = self.cleaned_data.get("carp_vhid")
        if val < 1 or val > 255:
            raise forms.ValidationError(
                _("This value must be between 1 and 255, inclusive.")
            )
        return val

    def clean_carp_skew(self):
        val = self.cleaned_data.get("carp_skew")
        if val < 2 or val > 254:
            raise forms.ValidationError(
                _("This value must be between 2 and 254, inclusive.")
            )
        return val

    def clean_carp_group(self):
        crit = self.cleaned_data.get('carp_critical')
        group = self.cleaned_data.get('carp_group')
        if crit is True and not group:
            raise forms.ValidationError(_('This field is required.'))
        return group

    def save(self):
        obj = super(CARPForm, self).save()
        notifier().start("network")
        notifier().start("ix-devd")
        return obj


class FailoverForm(ModelForm):

    class Meta:
        model = models.Failover

    def __init__(self, *args, **kwargs):
        super(FailoverForm, self).__init__(*args, **kwargs)
        self.fields['disabled'].widget.attrs['onChange'] = (
            'toggleGeneric("id_disabled", ["id_master"], true);'
        )
        if (
            self.instance.id and not self.instance.disabled
        ) or not self.instance.id:
            self.fields['master'].widget.attrs['disabled'] = 'disabled'

    def clean(self):
        if models.Failover.objects.count() > 0 and not self.instance.id:
            self._errors['__all__'] = self.error_class([
                _('Only one failover is allowed for now!')
            ])
        return self.cleaned_data

    def save(self, *args, **kwargs):
        if not self.instance.id:
            new = True
        else:
            new = False
        obj = super(FailoverForm, self).save(*args, **kwargs)
        if new:
            imported = False
            for vol in Volume.objects.filter(vol_fstype='ZFS'):
                try:
                    if notifier().zpool_parse(vol.vol_name):
                        imported = True
                        break
                except:
                    pass
            if imported:
                os.system('/usr/local/bin/python /usr/local/sbin/fenced force')
        notifier().start("ix-devd")
        return obj


class HAReplicationForm(Form):
    harepl_remote = forms.CharField(
        max_length=128,
        required=False,
        label=_('Remote Hostname'),
    )
    harepl_init = forms.BooleanField(
        initial=True,
        required=False,
        label=_('Initialize'),
    )

    def __init__(self, *args, **kwargs):
        super(HAReplicationForm, self).__init__(*args, **kwargs)
        harepl = notifier().harepl_get()
        if harepl:
            self.fields['harepl_remote'].initial = harepl[0]
            self.fields['harepl_init'].initial = harepl[1]

    def commit(self):
        notifier().harepl_set(
            remote=self.cleaned_data['harepl_remote'].__str__(),
            wantinit=self.cleaned_data['harepl_init'])
