# external imports
from flask_wtf import FlaskForm
from wtforms import StringField, SelectField, TextAreaField, SubmitField
from wtforms.validators import DataRequired, Length, NumberRange, Regexp, ValidationError

from webui.utils.form_validators import key_value_validator
from webui.proto.context_pb2 import (DeviceDriverEnum, DeviceOperationalStatusEnum)

class AddDeviceForm(FlaskForm):
    device_id = StringField('ID', 
                           validators=[DataRequired(), Length(min=5)])
    device_type = StringField('Type', 
                           validators=[DataRequired(), Length(min=5)])
    device_config = TextAreaField('Configurations', validators=[key_value_validator()])
    operational_status = SelectField('Operational Status',
                        #    choices=[(-1, 'Select...'), (0, 'Undefined'), (1, 'Disabled'), (2, 'Enabled')],
                           coerce=int,
                           validators=[NumberRange(min=0)])
    device_drivers = TextAreaField('Drivers', validators=[DataRequired(), Regexp(r'^\d+(,\d+)*$')])
    submit = SubmitField('Add')

    def validate_operational_status(form, field):
        if field.data not in DeviceOperationalStatusEnum.DESCRIPTOR.values_by_number:
            raise ValidationError('The operational status value selected is incorrect!')
    
    def validate_device_drivers(form, field):
        if ',' not in field.data:
            data = str(field.data) + ','
        else:
            data = field.data
        for value in data.split(','):
            value = value.strip()
            if len(value) == 0:
                continue
            try:
                value_int = int(value)
            except:
                raise ValidationError(f'The value "{value}" is not a valid driver identified.')
            if value_int not in DeviceDriverEnum.DESCRIPTOR.values_by_number:
                values = ', '.join([str(x) for x in DeviceDriverEnum.DESCRIPTOR.values_by_number])
                raise ValidationError(f'The device driver {value_int} is not correct. Allowed values are: {values}.')
