from flask import render_template, Blueprint, flash, session
from webui.Config import CONTEXT_SERVICE_ADDRESS, CONTEXT_SERVICE_PORT
from context.client.ContextClient import ContextClient
from webui.proto.context_pb2 import Empty
from webui.service.main.forms import ContextForm

main = Blueprint('main', __name__)

@main.route('/', methods=['GET', 'POST'])
def home():
    # flash('This is an info message', 'info')
    # flash('This is a danger message', 'danger')
    client: ContextClient = ContextClient(CONTEXT_SERVICE_ADDRESS, CONTEXT_SERVICE_PORT)
    client.connect()
    response = client.ListContextIds(Empty())
    print('received', len(response.context_ids), 'contexts')
    client.close()
    context_form: ContextForm = ContextForm()
    context_form.context.choices.append(('', 'Select...'))
    for context in response.context_ids:
        context_form.context.choices.append((context.context_uuid.uuid, context.context_uuid))
    if context_form.validate_on_submit():
        session['context_uuid'] = context_form.context.data
        flash(f'The context was successfully set to `{context_form.context.data}`.', 'success')
    else:
        print('form not validated')
    if 'context_uuid' in session:
        print('context exists in the session')
        context_form.context.data = session['context_uuid']
    else:
        print('context does not exist in the session')

    return render_template('main/home.html', context_form=context_form)
