# Copyright (c) 2015 iXsystems, Inc.
# All rights reserved.
# This file is a part of TrueNAS
# and may not be copied and/or distributed
# without the express permission of iXsystems.

import logging
import os

from django.utils.translation import ugettext_lazy as _

from dojango import forms

from freenasUI.account.models import bsdUsers
from freenasUI.common.forms import Form, ModelForm
from freenasUI.middleware.client import client
from freenasUI.middleware.form import MiddlewareModelForm
from freenasUI.middleware.notifier import notifier
from freenasUI.network.models import Interfaces
from freenasUI.storage.models import Volume

from . import models

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


class FailoverForm(MiddlewareModelForm, ModelForm):

    middleware_attr_schema = 'failover'
    middleware_attr_prefix = ''
    middleware_plugin = 'failover'
    is_singletone = True

    class Meta:
        model = models.Failover
        fields = '__all__'

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


class TakeoverForm(Form):

    password = forms.CharField(
        label="Root Password",
        widget=forms.widgets.PasswordInput(),
    )

    def clean_password(self):
        pwd = self.cleaned_data.get('password')
        qs = bsdUsers.objects.filter(bsdusr_uid=0)
        if qs.exists():
            user = qs[0]
            if not user.check_password(pwd):
                raise forms.ValidationError('Password invalid!')
            return pwd
        raise forms.ValidationError('Root user not found')


class UnlockForm(TakeoverForm):

    passphrase = forms.CharField(
        label="Passphrase",
        widget=forms.widgets.PasswordInput(),
    )
