# Copyright 2021-2023 H2020 TeraFlow (https://www.teraflow-h2020.eu/)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

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')
