# 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.

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, Set
from common.proto.context_pb2 import ContextId, Topology, TopologyId, TopologyIdList, TopologyList
from common.rpc_method_wrapper.ServiceExceptions import InvalidArgumentsException, NotFoundException
from common.tools.object_factory.Context import json_context_id
from common.tools.object_factory.Topology import json_topology_id
#from context.service.database.models.RelationModels import TopologyDeviceModel, TopologyLinkModel
from context.service.database.models.TopologyModel import TopologyModel
from .uuids.Context import context_get_uuid
from .uuids.Topology import topology_get_uuid

def topology_list_ids(db_engine : Engine, request : ContextId) -> TopologyIdList:
    context_uuid = context_get_uuid(request, allow_random=False)
    def callback(session : Session) -> List[Dict]:
        obj_list : List[TopologyModel] = session.query(TopologyModel).filter_by(context_uuid=context_uuid).all()
        #.options(selectinload(ContextModel.topology)).filter_by(context_uuid=context_uuid).one_or_none()
        return [obj.dump_id() for obj in obj_list]
    return TopologyIdList(topology_ids=run_transaction(sessionmaker(bind=db_engine), callback))

def topology_list_objs(db_engine : Engine, request : ContextId) -> TopologyList:
    context_uuid = context_get_uuid(request, allow_random=False)
    def callback(session : Session) -> List[Dict]:
        obj_list : List[TopologyModel] = session.query(TopologyModel).filter_by(context_uuid=context_uuid).all()
        #.options(selectinload(ContextModel.topology)).filter_by(context_uuid=context_uuid).one_or_none()
        return [obj.dump() for obj in obj_list]
    return TopologyList(topologies=run_transaction(sessionmaker(bind=db_engine), callback))

def topology_get(db_engine : Engine, request : TopologyId) -> Topology:
    _,topology_uuid = topology_get_uuid(request, allow_random=False)
    def callback(session : Session) -> Optional[Dict]:
        obj : Optional[TopologyModel] = session.query(TopologyModel)\
            .filter_by(topology_uuid=topology_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:
        context_uuid = context_get_uuid(request.context_id, allow_random=False)
        raw_topology_uuid = '{:s}/{:s}'.format(request.context_id.context_uuid.uuid, request.topology_uuid.uuid)
        raise NotFoundException('Topology', raw_topology_uuid, extra_details=[
            'context_uuid generated was: {:s}'.format(context_uuid),
            'topology_uuid generated was: {:s}'.format(topology_uuid),
        ])
    return Topology(**obj)

def topology_set(db_engine : Engine, request : Topology) -> bool:
    topology_name = request.name
    if len(topology_name) == 0: topology_name = request.topology_id.topology_uuid.uuid
    context_uuid,topology_uuid = topology_get_uuid(request.topology_id, topology_name=topology_name, allow_random=True)

    #device_uuids : Set[str] = set()
    #devices_to_add : List[Dict] = list()
    #for device_id in request.device_ids:
    #    device_uuid = device_id.device_uuid.uuid
    #    if device_uuid in device_uuids: continue
    #    devices_to_add.append({'topology_uuid': topology_uuid, 'device_uuid': device_uuid})
    #    device_uuids.add(device_uuid)

    #link_uuids : Set[str] = set()
    #links_to_add : List[Dict] = list()
    #for link_id in request.link_ids:
    #    link_uuid = link_id.link_uuid.uuid
    #    if link_uuid in link_uuids: continue
    #    links_to_add.append({'topology_uuid': topology_uuid, 'link_uuid': link_uuid})
    #    link_uuids.add(link_uuid)

    topology_data = [{
        'context_uuid' : context_uuid,
        'topology_uuid': topology_uuid,
        'topology_name': topology_name,
    }]

    def callback(session : Session) -> None:
        stmt = insert(TopologyModel).values(topology_data)
        stmt = stmt.on_conflict_do_update(
            index_elements=[TopologyModel.topology_uuid],
            set_=dict(topology_name = stmt.excluded.topology_name)
        )
        session.execute(stmt)

        #if len(devices_to_add) > 0:
        #    session.execute(insert(TopologyDeviceModel).values(devices_to_add).on_conflict_do_nothing(
        #        index_elements=[TopologyDeviceModel.topology_uuid, TopologyDeviceModel.device_uuid]
        #    ))

        #if len(links_to_add) > 0:
        #    session.execute(insert(TopologyLinkModel).values(links_to_add).on_conflict_do_nothing(
        #        index_elements=[TopologyLinkModel.topology_uuid, TopologyLinkModel.link_uuid]
        #    ))

    run_transaction(sessionmaker(bind=db_engine), callback)
    updated = False # TODO: improve and check if created/updated
    return TopologyId(**json_topology_id(topology_uuid, json_context_id(context_uuid))),updated

def topology_delete(db_engine : Engine, request : TopologyId) -> bool:
    _,topology_uuid = topology_get_uuid(request, allow_random=False)
    def callback(session : Session) -> bool:
        num_deleted = session.query(TopologyModel)\
            .filter_by(topology_uuid=topology_uuid).delete()
        return num_deleted > 0
    return run_transaction(sessionmaker(bind=db_engine), callback)
