# 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, Set
from common.proto.context_pb2 import ContextId, Topology, TopologyId, TopologyIdList, TopologyList
from common.rpc_method_wrapper.ServiceExceptions import NotFoundException
from context.service.database.models.RelationModels import TopologyDeviceModel
from context.service.database.models.TopologyModel import TopologyModel

def topology_list_ids(db_engine : Engine, request : ContextId) -> TopologyIdList:
    context_uuid = request.context_uuid.uuid
    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 = request.context_uuid.uuid
    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:
    context_uuid = request.context_id.context_uuid.uuid
    topology_uuid = request.topology_uuid.uuid

    def callback(session : Session) -> Optional[Dict]:
        obj : Optional[TopologyModel] = session.query(TopologyModel)\
            .filter_by(context_uuid=context_uuid, 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:
        obj_uuid = '{:s}/{:s}'.format(context_uuid, topology_uuid)
        raise NotFoundException('Topology', obj_uuid)
    return Topology(**obj)

def topology_set(db_engine : Engine, request : Topology) -> bool:
    context_uuid = request.topology_id.context_id.context_uuid.uuid
    topology_uuid = request.topology_id.topology_uuid.uuid
    topology_name = request.name

    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({
            'context_uuid': context_uuid, '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({
            'context_uuid': context_uuid, 'topology_uuid': topology_uuid, 'link_uuid': link_uuid
        })
        link_uuids.add(link_uuid)

    def callback(session : Session) -> None:
        topology_data = [{
            'context_uuid' : context_uuid,
            'topology_uuid': topology_uuid,
            'topology_name': topology_name,
            'created_at'   : time.time(),
        }]
        stmt = insert(TopologyModel).values(topology_data)
        stmt = stmt.on_conflict_do_update(
            index_elements=[TopologyModel.context_uuid, 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.context_uuid, TopologyDeviceModel.topology_uuid,
                    TopologyDeviceModel.device_uuid
                ]
            ))

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

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

def topology_delete(db_engine : Engine, request : TopologyId) -> bool:
    context_uuid = request.context_id.context_uuid.uuid
    topology_uuid = request.topology_uuid.uuid

    def callback(session : Session) -> bool:
        num_deleted = session.query(TopologyModel)\
            .filter_by(context_uuid=context_uuid, topology_uuid=topology_uuid).delete()
        return num_deleted > 0

    return run_transaction(sessionmaker(bind=db_engine), callback)
