import grpc
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 ContextId, ServiceList, ServiceTypeEnum, ServiceStatusEnum, ConfigActionEnum


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

context_client: ContextClient = ContextClient(CONTEXT_SERVICE_ADDRESS, CONTEXT_SERVICE_PORT)

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

    context_uuid = session['context_uuid']
    request: ContextId = ContextId()
    request.context_uuid.uuid = context_uuid
    context_client.connect()
    try:
        service_list: ServiceList = 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('detail/<service_uuid>')
def detail(service_uuid: str):
    flash('Detail service route called', 'danger')
    raise NotImplementedError()
    return render_template('service/home.html')
