from flask import session, current_app
from flask_security import current_user
from flask_wtf import FlaskForm
from wtforms import StringField, SelectField
from wtforms.validators import DataRequired, Optional
from wtforms_sqlalchemy.fields import QuerySelectField

from common.models.document import Catalog
from common.models.user import Tenant
from common.utils.database import Database


class SessionDefaultsForm(FlaskForm):
    user_name = StringField('User Name', validators=[DataRequired()])
    user_email = StringField('User', validators=[DataRequired()])

    # Tenant Defaults
    tenant_name = StringField('Tenant Name', validators=[DataRequired()])

    # Partner Defaults
    partner_name = StringField('Partner Name', validators=[DataRequired()])

    # Default Catalog - initialize as a regular SelectField
    catalog = SelectField('Catalog', choices=[], validators=[Optional()])

    def __init__(self):
        super().__init__()

        # Set basic fields first (these don't require DB access)
        self.user_name.data = current_user.user_name
        self.user_email.data = current_user.email
        self.tenant_name.data = session.get('tenant').get('name')
        if session.get('partner', None):
            self.partner_name.data = session.get('partner').get('name')
        else:
            self.partner_name.data = ""
        self.default_language.choices = [(lang, lang.lower()) for lang in
                                         current_app.config['SUPPORTED_LANGUAGES']]
        self.default_language.data = session.get('default_language')

        # Get a new session for catalog queries
        tenant_id = session.get('tenant').get('id')
        tenant_session = Database(tenant_id).get_session()
        try:
            # Populate catalog choices using tenant session
            catalogs = tenant_session.query(Catalog).all()
            self.catalog.choices = [(str(c.id), c.name) for c in catalogs]
            self.catalog.choices.insert(0, ('', 'Select a Catalog'))  # Add empty choice

            # Set current catalog if exists
            catalog_id = session.get('catalog_id')
            if catalog_id:
                self.catalog.data = str(catalog_id)
        finally:
            tenant_session.close()
