import logging
import sys
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__)

context_client: ContextClient = ContextClient(CONTEXT_SERVICE_ADDRESS, CONTEXT_SERVICE_PORT)

logger = logging.getLogger(__name__)

@main.route('/', methods=['GET', 'POST'])
def home():
    # flash('This is an info message', 'info')
    # flash('This is a danger message', 'danger')
    context_client.connect()
    response = context_client.ListContextIds(Empty())
    context_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')
    if 'context_uuid' in session:
        context_form.context.data = session['context_uuid']

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


@main.get('/about')
def about():
    return render_template('main/about.html')
