# 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 grpc
from flask import current_app, redirect, render_template, Blueprint, flash, session, url_for
from common.proto.context_pb2 import ContextId, Service, ServiceId, ServiceList, ServiceTypeEnum, ServiceStatusEnum, Connection
from context.client.ContextClient import ContextClient
from service.client.ServiceClient import ServiceClient

service = Blueprint('service', __name__, url_prefix='/service')

context_client = ContextClient()
service_client = ServiceClient()

@service.get('/')
def home():
    # flash('This is an info message', 'info')
    # flash('This is a danger message', 'danger')

    context_uuid = session.get('context_uuid', '-')
    if context_uuid == "-":
        flash("Please select a context!", "warning")
        return redirect(url_for("main.home"))
    request = ContextId()
    request.context_uuid.uuid = context_uuid
    context_client.connect()
    try:
        service_list = context_client.ListServices(request)
        # print(service_list)
        services = service_list.services
        context_not_found = False
    except grpc.RpcError as e:
        if e.code() != grpc.StatusCode.NOT_FOUND: raise
        if e.details() != 'Context({:s}) not found'.format(context_uuid): raise
        services = []
        context_not_found = True

    context_client.close()
    return render_template('service/home.html', services=services,
                                                context_not_found=context_not_found,
                                                ste=ServiceTypeEnum,
                                                sse=ServiceStatusEnum)


@service.route('add', methods=['GET', 'POST'])
def add():
    flash('Add service route called', 'danger')
    raise NotImplementedError()
    return render_template('service/home.html')


@service.get('<path:service_uuid>/detail')
def detail(service_uuid: str):
    context_uuid = session.get('context_uuid', '-')
    if context_uuid == "-":
        flash("Please select a context!", "warning")
        return redirect(url_for("main.home"))
    
    request: ServiceId = ServiceId()
    request.service_uuid.uuid = service_uuid
    request.context_id.context_uuid.uuid = context_uuid
    try:
        context_client.connect()
        response: Service = context_client.GetService(request)
        connections: Connection = context_client.ListConnections(request)
        context_client.close()
    except Exception as e:
        flash('The system encountered an error and cannot show the details of this service.', 'warning')
        current_app.logger.exception(e)
        return redirect(url_for('service.home'))
    return render_template('service/detail.html', service=response, connections=connections,ste=ServiceTypeEnum,
                                                sse=ServiceStatusEnum)


@service.get('<path:service_uuid>/delete')
def delete(service_uuid: str):
    context_uuid = session.get('context_uuid', '-')
    if context_uuid == "-":
        flash("Please select a context!", "warning")
        return redirect(url_for("main.home"))

    try:
        request = ServiceId()
        request.service_uuid.uuid = service_uuid
        request.context_id.context_uuid.uuid = context_uuid
        service_client.connect()
        response = service_client.DeleteService(request)
        service_client.close()

        flash('Service "{:s}" deleted successfully!'.format(service_uuid), 'success')
    except Exception as e:
        flash('Problem deleting service "{:s}": {:s}'.format(service_uuid, str(e.details())), 'danger')
        current_app.logger.exception(e)
    return redirect(url_for('service.home'))