from flask import current_app
from flask_wtf import FlaskForm
from wtforms.fields.choices import SelectField
from wtforms.fields.simple import SubmitField, StringField, BooleanField, TextAreaField
from wtforms.validators import DataRequired, Optional, Length

from common.extensions import cache_manager
from common.utils.form_assistants import validate_json
from eveai_app.views.dynamic_form_base import DynamicFormBase


class TriggerActionForm(FlaskForm):
    submit = SubmitField('Submit')


class EditPartnerForm(FlaskForm):
    tenant = StringField('Tenant', validators=[DataRequired()], render_kw={'readonly': True})
    code = StringField('Code', description="Referral Code", validators=[DataRequired()], render_kw={'readonly': True})
    logo_url = StringField('Logo URL', validators=[Optional(), Length(max=255)])
    active = BooleanField('Active', validators=[Optional()], default=True)


class PartnerServiceForm(FlaskForm):
    name = StringField('Name', validators=[DataRequired(), Length(max=50)])
    description = TextAreaField('Description', validators=[Optional()])
    type = SelectField('Partner Service Type', validators=[DataRequired()])
    active = BooleanField('Active', validators=[Optional()], default=True)

    user_metadata = TextAreaField('User Metadata', validators=[Optional(), validate_json])
    system_metadata = TextAreaField('System Metadata', validators=[Optional(), validate_json])

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # Dynamically populate the 'type' field
        types_dict = cache_manager.partner_services_types_cache.get_types()
        self.type.choices = [(key, value['name']) for key, value in types_dict.items()]


class EditPartnerServiceForm(DynamicFormBase):
    name = StringField('Name', validators=[DataRequired(), Length(max=50)])
    description = TextAreaField('Description', validators=[Optional()])
    type = StringField('Partner Service Type', validators=[DataRequired()], render_kw={'readonly': True})
    type_version = StringField('Partner Service Type Version', validators=[DataRequired()], render_kw={'readonly': True})
    active = BooleanField('Active', validators=[Optional()], default=True)

    user_metadata = TextAreaField('User Metadata', validators=[Optional(), validate_json])
    system_metadata = TextAreaField('System Metadata', validators=[Optional(), validate_json])
