from flask import flash, redirect, render_template, render_template_string, request
from indico.core import signals
from indico.core.db import db
from indico.core.plugins import IndicoPlugin, IndicoPluginBlueprint
from indico.modules.users.controllers import (
    RHPersonalData,
    RHPersonalDataUpdate,
    UserPersonalDataSchema,
)
from indico.web.flask.util import url_for
from indico.web.forms.base import IndicoForm
from indico.web.views import WPBase
from wtforms.fields import StringField
from wtforms.validators import Optional

from indico_custom_profile_fields.models.custom_fields import UserCustomProfile


class CustomProfileFieldsPlugin(IndicoPlugin):
    """Custom Profile Test Plugin"""

    def init(self):
        super().init()
        self.inject_bundle("main.js")

        # Hook into profile page to prefill custom fields
        # signals.rh.before_process.connect(
        #     self._prefill_custom_fields, sender=RHPersonalData
        # )
        signals.plugin.schema_post_dump.connect(
            self._prefill_custom_fields, sender=UserPersonalDataSchema
        )
        # Hook into profile update to handle custom field updates
        signals.rh.process.connect(
            self._after_profile_update, sender=RHPersonalDataUpdate
        )

    def _after_profile_update(self, sender, result, **kwargs):
        """Handle custom profile field updates after personal data update."""
        # Get the form data from the request
        print(sender)
        print(result)
        print(f" Kwargs: {kwargs}")
        print(kwargs.get("rh"))
        print(request.json)
        print(request.form)
        if sender is not RHPersonalDataUpdate:
            print("Not a personal data update request, skipping.")
            return
        form_data = request.json
        rh = kwargs.get("rh")

        # Check if test field is present in the form data
        if "testfield" in form_data:
            # Get or create the custom profile for the user
            custom_profile = UserCustomProfile.get_for_user(rh.user)
            print(custom_profile)

            # Update the test field
            custom_profile.testfield = form_data["testfield"]

            # Save to database
            db.session.add(custom_profile)
            db.session.commit()

    def _prefill_custom_fields(self, sender, **kwargs):
        print(sender)
        # print(result)
        print(f" Kwargs: {kwargs}")
        rh = kwargs.get("rh")
        print(rh)
        print(request)
        user = kwargs.get("orig")[0]
        print(user)
        custom_profile = UserCustomProfile.get_for_user(user)
        if custom_profile and custom_profile.testfield:
            kwargs["data"][0]["testfield"] = custom_profile.testfield
