# 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 time
from sqlalchemy.dialects.postgresql import insert
from sqlalchemy.engine import Engine
from sqlalchemy.orm import Session, sessionmaker
from sqlalchemy_cockroachdb import run_transaction
from typing import Dict, List, Optional
from common.proto.context_pb2 import Context, ContextId, ContextIdList, ContextList
from common.rpc_method_wrapper.ServiceExceptions import InvalidArgumentException, NotFoundException
from context.service.database.models.ContextModel import ContextModel

def context_list_ids(db_engine : Engine) -> ContextIdList:
    def callback(session : Session) -> List[Dict]:
        obj_list : List[ContextModel] = session.query(ContextModel).all()
        #.options(selectinload(ContextModel.topology)).filter_by(context_uuid=context_uuid).one_or_none()
        return [obj.dump_id() for obj in obj_list]
    return ContextIdList(context_ids=run_transaction(sessionmaker(bind=db_engine), callback))

def context_list_objs(db_engine : Engine) -> ContextList:
    def callback(session : Session) -> List[Dict]:
        obj_list : List[ContextModel] = session.query(ContextModel).all()
        #.options(selectinload(ContextModel.topology)).filter_by(context_uuid=context_uuid).one_or_none()
        return [obj.dump() for obj in obj_list]
    return ContextList(contexts=run_transaction(sessionmaker(bind=db_engine), callback))

def context_get(db_engine : Engine, request : ContextId) -> Context:
    context_uuid = request.context_uuid.uuid
    def callback(session : Session) -> Optional[Dict]:
        obj : Optional[ContextModel] = session.query(ContextModel)\
            .filter_by(context_uuid=context_uuid).one_or_none()
        return None if obj is None else obj.dump()
    obj = run_transaction(sessionmaker(bind=db_engine), callback)
    if obj is None: raise NotFoundException('Context', context_uuid)
    return Context(**obj)

def context_set(db_engine : Engine, request : Context) -> bool:
    context_uuid = request.context_id.context_uuid.uuid
    context_name = request.name

    for i, topology_id in enumerate(request.topology_ids):
        topology_context_uuid = topology_id.context_id.context_uuid.uuid
        if topology_context_uuid != context_uuid:
            raise InvalidArgumentException(
                'request.topology_ids[{:d}].context_id.context_uuid.uuid'.format(i), topology_context_uuid,
                ['should be == {:s}({:s})'.format('request.context_id.context_uuid.uuid', context_uuid)])

    for i, service_id in enumerate(request.service_ids):
        service_context_uuid = service_id.context_id.context_uuid.uuid
        if service_context_uuid != context_uuid:
            raise InvalidArgumentException(
                'request.service_ids[{:d}].context_id.context_uuid.uuid'.format(i), service_context_uuid,
                ['should be == {:s}({:s})'.format('request.context_id.context_uuid.uuid', context_uuid)])

    for i, slice_id in enumerate(request.slice_ids):
        slice_context_uuid = slice_id.context_id.context_uuid.uuid
        if slice_context_uuid != context_uuid:
            raise InvalidArgumentException(
                'request.slice_ids[{:d}].context_id.context_uuid.uuid'.format(i), slice_context_uuid,
                ['should be == {:s}({:s})'.format('request.context_id.context_uuid.uuid', context_uuid)])

    def callback(session : Session) -> None:
        context_data = [{
            'context_uuid': context_uuid,
            'context_name': context_name,
            'created_at'  : time.time(),
        }]
        stmt = insert(ContextModel).values(context_data)
        stmt = stmt.on_conflict_do_update(
            index_elements=[ContextModel.context_uuid],
            set_=dict(context_name = stmt.excluded.context_name)
        )
        session.execute(stmt)

    run_transaction(sessionmaker(bind=db_engine), callback)
    return False # TODO: improve and check if created/updated

def context_delete(db_engine : Engine, request : ContextId) -> bool:
    context_uuid = request.context_uuid.uuid
    def callback(session : Session) -> bool:
        num_deleted = session.query(ContextModel).filter_by(context_uuid=context_uuid).delete()
        return num_deleted > 0
    return run_transaction(sessionmaker(bind=db_engine), callback)
